TExcelTAD
Home › Ruby › Ruby Booleans & nil

Ruby Booleans & nil

Ruby has two boolean values, true and false, and a special value nil meaning "nothing here". The rules for what counts as true in a condition are short — and different from many other languages.

true, false and nil are objects

ruby · try it yourself
p true.class
p false.class
p nil.class
p true & false
p true ^ true
p nil.to_a
p nil.to_s
p nil.inspect
TrueClass
FalseClass
NilClass
false
false
[]
""
"nil"

Truthy and falsy

This is the most important rule in this lesson:

Only false and nil are falsy. Everything else is truthy — including 0, "", [] and {}.

ruby · try it yourself
[false, nil, 0, "", [], {}, "false", true].each do |value|
  verdict = value ? "truthy" : "falsy"
  puts "#{value.inspect.ljust(8)} -> #{verdict}"
end
false    -> falsy
nil      -> falsy
0        -> truthy
""       -> truthy
[]       -> truthy
{}       -> truthy
"false"  -> truthy
true     -> truthy

Coming from Python or JavaScript, the surprises are 0, "" and [] being truthy. To test for emptiness, ask explicitly: list.empty?, text.empty?, n.zero?.

Value Ruby Python JavaScript
0 truthy falsy falsy
"" truthy falsy falsy
[] truthy falsy truthy
nil / None / null falsy falsy falsy

Predicate methods

Methods that answer a yes/no question end with ? by convention and return true or false:

ruby · try it yourself
p [].empty?
p "abc".include?("b")
p 9.odd?
p nil.nil?
p 0.nil?
p "".empty?
p [1, nil, 2].any?(nil)
p [2, 4, 6].all?(&:even?)
true
true
true
true
false
true
true
true

Where nil comes from

nil appears whenever "there is no value":

ruby · try it yourself
p [1, 2, 3][10]
p({a: 1}[:b])
p "hello".index("z")
p [5, 7].find { |n| n > 100 }

def nothing
end
p nothing
p (puts "printed")
nil
nil
nil
nil
nil
printed
nil
  • Out-of-range array index → nil
  • Missing hash key → nil
  • A search with no match → nil
  • A method with an empty body → nil
  • puts returns nil

Handling nil safely

Calling a method on nil that it doesn't have raises NoMethodError — the most common Ruby error. You have several tools to avoid it:

ruby · try it yourself
city = nil

# 1. Default with ||
p (city || "Unknown")

# 2. Safe navigation &.
p city&.upcase

# 3. Explicit check
puts city.nil? ? "no city" : city

# 4. Convert: nil.to_s is ""
p city.to_s.upcase

# 5. What happens without protection
begin
  city.upcase
rescue NoMethodError => e
  puts "Error: #{e.message}"
end
"Unknown"
nil
no city
""
Error: undefined method 'upcase' for nil

Converting to a real boolean

Sometimes you need true/false instead of a truthy value. The double bang !! does it:

ruby · try it yourself
name = "Ada"
missing = nil
p !!name
p !!missing
p name.nil?
p missing.nil?
true
false
false
true

compact: removing nils

Arrays often collect nil values. compact removes them:

ruby · try it yourself
p [3, nil, 8, nil, 1].compact
p ["a", nil, "b"].map { |s| s&.upcase }
[3, 8, 1]
["A", nil, "B"]

Tip: When a method may return nil, decide right away what should happen: provide a default (|| 0), skip it (&.), or fail loudly (fetch on a hash raises a clear error instead of returning nil).

Test yourself

Which of these values is falsy in Ruby?

  1. 0
  2. ""
  3. []
  4. nil

What does [10, 20][5] return?

  1. 0
  2. nil
  3. IndexError
  4. 20

What is !!"hello"?

  1. "hello"
  2. true
  3. false
  4. nil