Truthiness: only false and nil
| Only false and nil are falsy | |
| Zero is truthy | |
| Empty is truthy | |
| Use it for guards |
Only false and nil are falsy
Every Ruby value counts as true in a condition except two: false and nil. nil means no value, the answer you get when something is missing.
Both lines below stay silent because their conditions are falsy, so only the last line prints:
puts "hi" if false
puts "hi" if nil
puts "done"
done
Zero is truthy
In some languages zero behaves like false, but not in Ruby. The number zero is an ordinary truthy value, so a counter reaching zero still passes the check.
if 0
puts "zero is truthy"
end
zero is truthy
Empty is truthy
Empty values are truthy as well. An empty string and an empty array both pass the check: only false and nil can stop a condition.
if ""
puts "empty string is truthy"
end
if []
puts "empty array is truthy"
end
empty string is truthy
empty array is truthy
Use it for guards
Truthiness shines in small guard lines that handle the missing case first. Ask whether a value is nil, print a fallback, and let the rest of the code assume a real value.
name = nil
puts "guest" if name.nil?
guest
Flip the variable to a real string and the guard stays silent. The next lesson builds full if and else branches on top of this idea.
Next: Conditions
Article author: Arthur Isaev