-1

I was doing something and I find bit confusing && operator functionality.

When I do

5 || 15
=> 5

nil || 15
=> 15

5 || nil
=> 5

But when I do it with && operator.

5 && 15
=> 15

nil && 15
=> nil

5 && nil
=> nil

Can someone help me understand ?

Anuj
  • 1,737
  • 3
  • 16
  • 29

1 Answers1

3

Boolean operators in ruby are short-circuiting: if it is possible to determine the value of the expression from the left-hand argument, the right-hand argument isn't evaluated.

Therefore, a simpler mental model for evaluation of a boolean expression involving && is to consider first expressions involving only two operands: the left-hand operand is evaluated first; if the value of this operand is nil or false, the operand is returned and the right-hand operand isn't evaluated; if the left-hand operand is anything else, the right-hand operator is evaluated and its value is returned.

From this definition, it's clear that, as you note, expressions involving boolean operators don't return true or false, but simply a true value or a false value. It's worth noting that this doesn't make any difference in a context where a boolean expression is used only for its true-ness or false-ness.

Hope it will help you.