Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

false && nil and nil && false in ruby

Tags:

ruby

Why does nil && false return nil while false && nil returns false?

I read the top answer in nil || false and false || nil in ruby. It seems to me that both nil and false evaluate as falsy value, but why do these two expressions return different values?

like image 573
Zzz Avatar asked Feb 28 '26 22:02

Zzz


1 Answers

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.

like image 87
Yu Hao Avatar answered Mar 02 '26 15:03

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!