24

In Ruby, why are the following lines true?

0 && 1 == 1 1 && 0 == 0 

Why are they different and aren't both 0?

3 Answers 3

37

Boolean AND operator && returns its second operand if first is not false. 0 and 1 are true in boolean expressions in Ruby. Only nil and false are false in boolean expressions.

nil && 15 # => nil 15 && 17 # => 17 15 && nil # => nil 
Sign up to request clarification or add additional context in comments.

Comments

7

0 and 1 don't represent truth values in Ruby. In ruby anything that is not nil or false is true. If you add to this that:

The and and && operators evaluate their first operand. If false, the expression returns false; otherwise, the expression returns the value of the second operand.

You get that you evaluate true && true and then the result of the second operand is returned. If you wrote 3 && 4, you would have gotten 4!

Comments

3

In addition to excellent answers here:

You probably confuse logical and bitwise ANDs.

$ irb 1.9.3-p125 :001 > 1 & 0 => 0 1.9.3-p125 :002 > 0 & 1 => 0 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.