What Evaluates to False in Ruby

What evaluates to false in Ruby?

false and nil are the only ones:

http://www.ruby-doc.org/core-2.1.1/FalseClass.html

Rails provides present? which also includes empty strings and empty arrays: http://api.rubyonrails.org/classes/Object.html#method-i-present-3F

if(!x) vs if(x==false) in ruby

Ruby considers that false and nil are the only two "falsy" values, while everything else is "truthy". This is by definition and can not be modified (at least in MRI). This definition is used for all builtin operators like if, unless, while, until, cond ? if_truthy : if_falsey, ||, &&, ...

Writing foo == bar will always call the == method on foo with bar as an argument. By default, nil, false, true and all other immediates like symbols, etc..., are only equal to themselves. This could be changed, though:

def nil.==(bar)
super || bar == false
end
puts "nil == false" if nil == false # => "nil == false"

In Ruby 1.9, you can also redefine the operator !, so unless foo is not necessarily the same as if !foo or the contrary of if foo:

def true.!
true
end

puts "True?" if true # => "True?"
puts "or not?" if !true # => "or not?"

Not that anybody would recommend doing anything like this...

Ruby: why does =~ evaluate to true in an if statement?

The predicate after if will be treated as a boolean value.

In Ruby, only false and nil are treated as false. Anything other will be evaluated to true, so 0, [], {} are all true in boolean context.

From Ruby doc:

nil and false are both false values. nil is sometimes used to indicate "no value" or "unknown" but evaluates to false in conditional expressions.

true is a true value. All objects except nil and false evaluate to a true value in conditional expressions.

And you may have a look at the control expressions.

false && nil and nil && false in ruby

The rule is simple: && returns its first argument if it is falsy. Otherwise, it evaluate and returns its second argument.

So in

nil && false

and

false && nil

In both cases, the first argument is falsy. (nil and false are the only two values that evaluate falsy), so the result of the expression is the first argument.

The fact that the second argument also happens to be false doesn't matter. In fact, the second argument isn't evaluated because of short-circuit.

Nil and boolean in Ruby

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.

nil || false and false || nil in ruby

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.



Related Topics



Leave a reply



Submit