Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variable only if not nil

I have @obj.items_per_page, which is 20 at the beginning, and I want the method below to assign value to it only if many_items is not nil:

def fetch_it_baby (many_items = nil)
    @obj.items_per_page = many_items

With the code above, even if many_items is nil, @obj.items_per_page remains at 20. Why? And is that "good" coding? Shouldn't I use something like

@obj.items_per_page = many_items || @obj.items_per_page

Or is there a third way? I don't feel completely comfortable with either way.

like image 595
Juuro Avatar asked Oct 01 '13 10:10

Juuro


1 Answers

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
like image 158
user Avatar answered Sep 16 '22 15:09

user