Booleans and nil
Prerequisites: Data types
A boolean is a yes/no value: true or false. Comparisons produce
booleans:
p 5 > 3
p 5 == 3
p "ruby" == "ruby"
true
false
true
nil means "no value at all". It's what you get when something is
missing — for example, looking up a hash key that doesn't exist, or a
method that has nothing to return.
scores = { ada: 90 }
p scores[:bob]
p nil.nil?
p 0.nil?
nil
true
false
Truthiness: only nil and false are falsy
When Ruby checks a condition, only false and nil count as false.
Everything else — including 0, "" (an empty string), and [] (an
empty array) — counts as true. This is different from Python,
JavaScript, and PHP, where 0 and "" are falsy.
count = 0
name = ""
missing = nil
puts "0 is truthy" if count
puts "empty string is truthy" if name
puts "nil is falsy" unless missing
0 is truthy
empty string is truthy
nil is falsy
To check for "empty", ask explicitly: name.empty?, list.empty?,
count.zero?.
Common mistakes
- Calling a method on
nilby accident.nil.upcaseraisesundefined method 'upcase' for nil (NoMethodError)— the most common error in Ruby. It means a value you expected to exist was missing. - Writing
if countto mean "if count isn't zero". It's always true for any number; writeif count.positive?orif count > 0.
Practice
Predict which of these lines print, then run them to check.
puts "A" if []
puts "B" if false
puts "C" if "false"
Show solution
A and C print. An empty array is truthy, and "false" is a
non-empty string, so it's truthy too. Only the real false value on
line 2 is falsy.
A
C