Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nil || false and false || nil in ruby

Tags:

null

ruby

nil || false returns false and false || nil returns nil. Does anyone have an explanation for this?

like image 553
user1538814 Avatar asked Oct 03 '12 04:10

user1538814


People also ask

Is false == nil 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 false in Ruby?

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.

What does nil mean in Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value.


1 Answers

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.

like image 145
x1a4 Avatar answered Nov 02 '22 20:11

x1a4