Ruby Quickies #1

A tale of “&&” and “||”

In ruby, the operators “&&” and “||” in ruby statements (not if-stmts) have some special properties.

Let’s see how:

stmt1 && stmt2
returns the first falsey result, or if no falsey’s found, returns the last truthy result
example:

‘hello’ && ‘bye’
# => ‘bye’
‘hello’ && false
# => false
false && ‘hello’
# => false
nil && false && ‘hello’
# => nil
‘hello’ && false && nil && ‘bye’
# => false

stmt1 || stmt2
returns the first truthy result, or if no truthy’s found, returns the last falsey result
example:

‘hello’ || ‘bye’
# => ‘hello’
‘hello’ || false
# => ‘hello’
false || ‘hello’
# => ‘hello’
nil || false || ‘hello’
# => ‘hello’
false || nil
# => nil
nil || false
# => false

In summary, if falsey’s break &&, and if truthy’s break ||:
If breakers found, stop there, and return the result at that point.
If NO breakers found, continue executing until the end, and then return the last result.

So, how’s this useful?
Well, we can use a chaining of && and || to rewrite some if-stmts, for example:

if x > 5
puts “greater”
else
puts “smaller”
end

You can rewrite this as:

puts x>5 && “greater” || “smaller”

Done! easy breezy short form.

A word of caution: pay attention when mixing &&’s and ||’s to use parentheses to make sure precedence is evaluated correctly.