nil || false
returns false
and false || nil
returns nil
. Does anyone have an explanation for this?
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, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass.
Well, nil is a special Ruby object used to represent an “empty” or “default” value.
In Ruby, everything is an expression, and an expression will return the last value evaluated within it.
For both of your examples, the left side of the ||
expression evaluates to a falsy value, so Ruby then evaluates the right side, and returns it.
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