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
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.
Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false and nil are “falsey,” everything else is “truthy.”
In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .
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.
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