Assign variable only if not nil

The style I generally see looks like this:

@obj.items_per_page = many_items if many_items

This uses the inline conditional, while avoiding negative or double-negative conditions.


You can use &&= (in the same way as ||= is used to assign only if nil or false)

> a = 20    # => 20 
> a &&= 30  # => 30
> a         # => 30
> a = nil   # => nil
> a &&= 30  # => nil
> a = false # => false
> a &&= 30  # => false
> a = {}    # => {}
> a &&= 30  # => 30

remember though

> a = 30      # => 30
> a &&= nil   # => nil
> a &&= false # => nil
> b &&= 3     # => nil

Even if many_items is nil @obj.items_per_page remains at 20

That sounds like whatever class @obj is has a custom modifier method items_per_page= that only updates the value if the new value is not nil. This is not standard Ruby. For example, given this definition:

class Demo
  attr_accessor :items_per_page
end

I get this behavior:

irb(main):005:0>     demo = Demo.new           #=> #<Demo:0x007fb7b2060240>
irb(main):006:0>     demo.items_per_page = 20  #=> 20
irb(main):007:0>     demo.items_per_page       #=> 20
irb(main):008:0>     demo.items_per_page = nil #=> nil
irb(main):009:0>     demo.items_per_page       #=> nil

As for your example, I would probably write it this way:

@obj.items_per_page = many_items unless many_items.nil?

I suggest the following as it makes it clear that you have a default value for the assignment in case the caller did not specify many_items in the call:

def function(argument = nil)
  variable = argument || 20
  ...
end

However, since you specified that the assignment takes places only if the value is not nil then you'll need to check for the nil value otherwise you will miss the assignment if the value was false. If you really need that case then the solution is more long-winded:

def function(argument = nil)
  variable = argument.nil? ? 20 : argument
  ...
end