Skip to the workspace
Pebellslearn by building
Data Types  ›  Lesson

Booleans and nil

Booleans 12 minIn Ruby only false and nil are falsy, so zero, empty strings and empty arrays all count as true in a condition.

ruby / Booleans and nil

Explore each scene at your own pace.

01 · The rule

The rule

Booleans and nil

In Ruby only false and nil are falsy, so zero, empty strings and empty arrays all count as true in a condition.

Trace conditions involving false, nil, zero and empty strings.

Bean Cart's script checks if cups_left to decide whether to take another order. With 0 cups left, it still says yes. A programmer from Python or JavaScript expects 0 to count as "false", but Ruby has a much shorter list of false things, and that list is worth memorising.

The rule

Only false and nil are falsy; everything else is truthy.

Ruby's booleans are the two objects true and false. They belong to the classes TrueClass and FalseClass; there is no single Boolean class.

nil means "no value here". It is the only object of class NilClass. You get it when something is missing:

MENU = { latte: 4.50 }
MENU[:chai]      # => nil  (no such key)
[1, 2][5]        # => nil  (no such index)
puts "hi"        # returns nil

In a condition, Ruby does not need a real boolean. It only asks: "is this false or nil?" If not, the condition passes. So all of these are truthy: 0, "", [], {}, "false", 0.0.

cups_left = 0
if cups_left
  puts "Take order"   # this runs: 0 is truthy
end

if cups_left > 0      # the real question
  puts "Take order"
end

To test for nil specifically, ask the object: price.nil?. To test for "empty", ask that instead: name.empty?, orders.empty?, cups_left.zero?.

nil has safe conversions that come up often: nil.to_s is "", nil.to_a is [], and nil.to_i is 0. And the safe navigation operator &. calls a method only if the object is not nil:

customer = nil
customer&.upcase   # => nil, instead of a NoMethodError
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.