Lesson 5 of 23 · Ruby 4.0
Represent yes, no and absence
Read boolean results and distinguish false values from absent values.
Learn
The values true and false represent yes-or-no results. A comparison such as tickets == 0 tests equality; tickets > 0 tests whether tickets is greater than zero. Each comparison produces a boolean that you can display with p.
nil commonly represents a missing or unknown value. It is a distinct value from false. Use p to make nil visible, and use value.nil? to test whether a value is nil. The question mark is part of this method name.
Ruby treats false and nil as false in truth tests, and every other value as true; this property is called truthiness. The ! operator negates that truthiness: !value is true for a false value and false for a true value. In particular, zero and an empty string are both truthy.
Example
tickets = 3
p tickets > 0
p tickets == 0
arrival = nil
p arrival
p arrival.nil?Experiment
Predict the comparisons, then run. Change booked to 10 and consider why equality and greater-than can give different answers.
Predict the results of negating these four values, then run. Replace the empty string with "ready" and compare that line again.