Ruby Nil and Boolean – Understanding Their Differences

rubyruby-on-rails

Can someone explain the reasoning being this? Just spent 30 mins trying to figure out why my boolean method returned nil and found out that in Ruby:

2.2.1 :001 > nil && true
 => nil
2.2.1 :002 > nil && false
 => nil

Since nil is a falsey value, I would have expected the output of nil && true to be false. Also it seems to go against the idea that conditional operators should return a boolean value.

What is the rationale behind this?

It makes sense that the boolean operator is not commutative:

nil && false != false && nil

For others seeing this, my issue was that in rails I had a statement like:

def some_method?
  object.attr && object.attr > something
end

But when object.attr is nil, the function will be nil. Which is fine in most cases but when chaining boolean methods together, not so much. I just changed it to this instead:

def some_method?
  object.attr.present? && object.attr > something
end

I could do the same thing in vanilla Ruby with:

def some_method?
  !!object.attr && object.attr > something
end

Best Answer

The statement goes through the conditions in order, will stop when a falsy result is obtained and return the value of the last evaluation performed.

In contrary to && which stops at a falsy value, || will stop at a truthy value instead.