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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With