Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nil and boolean in Ruby

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
like image 923
onetwopunch Avatar asked Jan 29 '16 18:01

onetwopunch


People also ask

What is nil in Ruby?

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.

Is nil true in Ruby?

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.”

What is a boolean in Ruby?

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 .


1 Answers

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.

like image 57
Edward Avatar answered Oct 04 '22 10:10

Edward