The Analogy: The Usher At The Ticket Door
It is Friday evening at a repertory theatre and one usher is working the door to house two. There is a queue behind every patron, so she has learned a short sequence of questions and she asks them in the same order every time, chosen so that the quickest and most decisive question comes first. Is there a ticket at all. Is it for tonight. Is it for this house. Is the seat one that this door actually leads to. Any of those can end the conversation on the spot, and once it ends, nothing further about the ticket matters. She does not read the seat number on a ticket printed for Thursday.
She is not only deciding, she is producing something. A stamp on the back of the hand, a torn stub handed back, a spoken direction: stalls, rear, on your left. The patron carries that result onward and the bar staff and the seat steward both rely on it. This is exactly what Ruby's conditionals do. An if is not a statement that performs a jump and leaves nothing behind, it is an expression whose value is the value of whichever branch ran. You can assign the result of a decision to a name the way the usher hands over a stub, and most of the time you should.
The door has exactly two grounds for refusal: there is no ticket, or the ticket is not valid. Everything else gets in, including things that look odd at first glance. A comp with a face value of zero pounds is a real ticket. A ticket with no name printed on it is a real ticket. A party booking that turns out to list no guests is still a real booking. Ruby draws the same line in the same place, and it is the line that surprises people arriving from other languages: only nil and false are refusals. 0 is admitted. "" is admitted. [] and {} are admitted. There is no third category of nearly-false.
The failure modes are all about order and about signs nobody can read. An usher who tears the stub before checking the night has destroyed a refundable ticket to learn something she could have learned first, which is what happens when code mutates state above the guard that would have rejected it. An usher working from a sign that says "do not admit unless the ticket is not for another house" will guess, and so will the next person to read your unless with an else attached to it. And an usher who waves through a blank ticket because it is not obviously invalid has made the truthiness mistake in person: the empty string is not a refusal, so if you want it treated as one you have to say so. All three failures are paid for by the same people, the ones still standing outside in the rain while the queue does not move.
Syntax or Core Structure
Every conditional form Ruby offers is in the program below, arranged in the order the usher would use them: guards first, then a branch that produces a value, then the modifier forms for one-line decisions, then case for a single subject tested several ways.
# door.rb -- the checks an usher makes, in the order she makes them.
def verdict(ticket)
return "no ticket" if ticket.nil?
return "wrong night" unless ticket[:night] == "friday"
return "wrong house" unless ticket[:house] == 2
"row #{ticket[:row]}, seat #{ticket[:seat]}"
end
puts verdict(nil)
puts verdict({ night: "thursday", house: 2, row: 4, seat: 11 })
puts verdict({ night: "friday", house: 1, row: 4, seat: 11 })
puts verdict({ night: "friday", house: 2, row: 4, seat: 11 })
# if is an expression: the value of the branch that ran is the value of the whole.
age = 15
band =
if age < 5 then "infant"
elsif age < 16 then "child"
else "adult"
end
puts band
# The modifier form reads as one sentence and needs no end.
puts "stamp the hand" if band != "infant"
puts "needs an adult" unless band == "adult"
# A ternary is for a genuine two-way choice that produces a value.
price = band == "child" ? 6 : 11
puts "price #{price}"
# case/when: one subject, several shapes of test.
row = 4
area =
case row
when 1..10 then "stalls"
when 11..12 then "circle"
else "unknown"
end
puts "row #{row} -> #{area}"
# Only two values are refusals. Everything else is admitted.
[nil, false, 0, "", [], "no"].each do |v|
puts "#{v.inspect.ljust(5)} #{v ? 'admitted' : 'refused'}"
end
Output:
no ticket
wrong night
wrong house
row 4, seat 11
child
stamp the hand
needs an adult
price 6
row 4 -> stalls
nil refused
false refused
0 admitted
"" admitted
[] admitted
"no" admitted
Read verdict from the top and you are reading the usher's sequence. Each return is a guard clause: a condition that, if met, ends the method immediately with a refusal. Because the refusals leave first, the last line of the method has no indentation and no conditions attached to it. It is the answer for a ticket that survived every check, and it is the only line in the method that describes success.
The band assignment shows the property that distinguishes Ruby's conditionals from those of C or Java. The whole if/elsif/else construct evaluates to "child", and that value is assigned once. There is no need to write band = "child" inside each branch, and no way to forget one of the assignments. The then keyword is what lets a branch sit on the same line as its condition; with a newline instead you would write the branches on their own lines and then becomes unnecessary.
The modifier forms at the bottom, puts "..." if cond and puts "..." unless cond, are for decisions short enough to read as one English sentence. unless is a negated if, so unless band == "adult" fires precisely when band is not "adult", which for our fifteen year old is true.
Technical Depth: What Counts As True, And What A Branch Hands Back
The Two Refusals, In Full
Ruby's rule for truth is the shortest one in any mainstream language, and it is worth learning as a closed list rather than as a feeling.
| Value | Admitted? | Worth knowing |
|---|---|---|
nil | no | the absence of a value, and one of exactly two refusals |
false | no | the boolean, and the other refusal |
0 | yes | zero is an ordinary Integer object like any other |
"" | yes | if emptiness is what you mean, call empty? |
" " | yes | a space is content; strip is how you find out that it is all there is |
[] | yes | for collections use empty? or any? |
{} | yes | and remember a missing key hands you nil, which is a refusal |
:sym | yes | every object other than the two above is admitted |
"false" | yes | a five character String, no relation to the boolean |
Because the list of refusals has exactly two entries, x.nil? and !x differ in exactly one circumstance: when x is false. That single circumstance is the source of a whole family of configuration bugs, because a setting the user deliberately switched off and a setting the user never mentioned are different facts that a bare truth test cannot tell apart.
Every Conditional Hands Something Back
# An if with no matching branch hands back nil, quietly.
stamp = if false then "stamped" end
puts stamp.inspect
# The logical operators hand back one of their operands, not a boolean.
a = nil || "fallback"
b = false || nil
c = 0 || 9
d = "a" && "b"
e = nil && raise("never reached")
f = !nil
puts a.inspect
puts b.inspect
puts c.inspect
puts d.inspect
puts e.inspect
puts f.inspect
# A ternary and a case are expressions in the same way.
seats = 0
note = seats.zero? ? "sold out" : "#{seats} left"
puts note
verdict =
case seats
when 0 then "sold out"
when 1..20 then "some left"
else "plenty"
end
puts verdict
Output:
nil
"fallback"
nil
0
"b"
nil
true
sold out
sold out
| Expression, described in words | Result | Why |
|---|---|---|
or, with nil on the left and "fallback" on the right | "fallback" | or hands back the first operand that is admitted |
or, with false on the left and nil on the right | nil | nothing was admitted, so the last operand comes back |
or, with 0 on the left and 9 on the right | 0 | zero is admitted, so the right side is never evaluated |
and, with "a" on the left and "b" on the right | "b" | and hands back the last operand when everything is admitted |
and, with nil on the left and a raise on the right | nil | the right side never runs, which is what makes chained guards safe |
!nil | true | the bang operator is the one form that always answers with a boolean |
The first line of the program is the one to remember. An if whose condition failed and which has no else is not an error and does not skip the assignment; it assigns nil.
when Uses The Threequal, Not Equals
A when clause does not test equality. It asks the object after when to judge the subject, by calling === on it. Since every class is free to define that method, the same syntax means six different things depending on what you put there.
The object after when | What the test actually means | A subject that matches |
|---|---|---|
| a Range | does the range cover the subject | 1..10 matches 4 |
| a Class or Module | is the subject an instance of it | Integer matches 7 |
| a Regexp | does the pattern match the subject | a room label pattern matches the string room 12 |
| a Proc or lambda | call it with the subject, then ask whether the answer is admitted | a lambda testing respond_to? matches an Array |
| a plain value | ordinary equality, since that is what === defaults to | "circle" matches "circle" |
| any object of your own | whatever that class defines === to mean | whatever its author decided |
ENUMERABLE = ->(v) { v.respond_to?(:each) }
def describe(x)
case x
when Integer then "an integer"
when /\Aroom \d+\z/ then "a room label"
when String then "some other string"
when ENUMERABLE then "enumerable"
else "something else"
end
end
puts describe(7)
puts describe("room 12")
puts describe("hello")
puts describe([1, 2])
puts describe(nil)
Output:
an integer
a room label
some other string
enumerable
something else
Order matters twice over here. Integer has to come before the lambda, because an Integer does not respond to each and would fall through anyway, but a Hash would match both. The room label pattern has to come before the bare String clause, because String matches every string including the room labels, and the first matching clause wins. Notice also that nil was compared against a Regexp without raising: Regexp#=== answers false for a non-string rather than complaining, which is convenient and occasionally hides a type error.
Ruby 3.0 added a second form, case with in instead of when, which matches a subject by its shape and binds names out of it in the same move. It is a different tool with a different failure mode -- with no else clause it raises NoMatchingPatternError rather than handing back nil -- and it is covered with the rest of pattern matching later in the track.
Guards Flatten The Door
Both methods below implement the same rule and hand back the same four answers. Only one of them can absorb a fifth check without a rewrite.
# The same rule, nested. Every real decision sits three levels in.
def nested(ticket)
if ticket
if ticket[:night] == "friday"
if ticket[:house] == 2
"admit"
else
"wrong house"
end
else
"wrong night"
end
else
"no ticket"
end
end
# The same rule, flattened. Refusals leave first and success stays at the margin.
def flat(ticket)
return "no ticket" unless ticket
return "wrong night" unless ticket[:night] == "friday"
return "wrong house" unless ticket[:house] == 2
"admit"
end
tickets = [nil, { night: "thursday" }, { night: "friday", house: 1 }, { night: "friday", house: 2 }]
tickets.each do |t|
puts "#{nested(t).ljust(12)}#{flat(t)}"
end
Output:
no ticket no ticket
wrong night wrong night
wrong house wrong house
admit admit
nil, false, And The Three Ways To Ask
config = { "retries" => nil, "verbose" => false }
puts config["retries"].inspect
puts config.fetch("retries", 3).inspect
puts config.fetch("timeout", 3).inspect
puts config.key?("retries")
fallback = config["retries"] || 3
puts fallback.inspect
flag = config["verbose"]
flag ||= true
puts flag.inspect
count = 0
count ||= 99
puts count
usher = nil
shouted = usher&.upcase
puts shouted.inspect
puts "on duty".upcase
Output:
nil
nil
3
true
3
true
0
nil
ON DUTY
Two lines in that output are the ones that cost people an afternoon. fetch("retries", 3) handed back nil, not 3, because the key was present and its value happened to be nil; a fetch default answers a missing key, not an empty one. And flag ||= true overwrote an explicit false, because ||= assigns whenever the current value is not admitted, and false is not admitted. ||= can therefore never be used to default a boolean setting.
Real World Example: The Door Book For A Friday House
One evening, nine tickets, one usher, and a report the duty manager reads at the end of it. The interesting part of this program is not that it decides; it is that every refusal has a name, and the names are what get counted.
# door_book.rb -- decide, count, and report on one evening at the door.
TICKETS = <<~ROWS
1902 friday 2 4 11 stalls
1904 friday 2 0 0 stalls
1907 thursday 2 6 3 stalls
1911 friday 1 2 8 stalls
1913 friday 2 12 2 circle
1915 friday 2 4 11 stalls
1922 friday 2 9 1 circle
1930 friday 2 5 0 stalls
1935 thursday 2 7 4 stalls
ROWS
Ticket = Struct.new(:minute, :night, :house, :row, :seat, :area)
def parse(text)
text.lines.map do |line|
hhmm, night, house, row, seat, area = line.split
Ticket.new(hhmm[0, 2].to_i * 60 + hhmm[2, 2].to_i, night, house.to_i, row.to_i, seat.to_i, area)
end
end
def area_for(row)
case row
when 1..10 then "stalls"
when 11..12 then "circle"
end
end
def verdict(t)
return "wrong night" unless t.night == "friday"
return "wrong house" unless t.house == 2
seated = area_for(t.row)
return "unseated" if seated.nil?
return "wrong area" unless seated == t.area
"admit #{t.area} row #{t.row} seat #{t.seat}"
end
tickets = parse(TICKETS)
results = tickets.map { |t| [t, verdict(t)] }
puts "presented: #{tickets.size}"
results.each do |t, v|
clock = format("%02d:%02d", t.minute / 60, t.minute % 60)
place = "r#{t.row.to_s.rjust(2)} s#{t.seat.to_s.rjust(2)}"
puts " #{clock} #{t.night.ljust(9)}h#{t.house} #{place} #{t.area.ljust(7)}#{v}"
end
admitted = results.count { |_t, v| v.start_with?("admit") }
puts "admitted #{admitted} refused #{results.size - admitted}"
reasons = Hash.new(0)
results.each { |_t, v| reasons[v] += 1 unless v.start_with?("admit") }
puts "refusals by reason:"
reasons.sort_by { |reason, n| [-n, reason] }.each do |reason, n|
puts " #{reason.ljust(12)}#{n}"
end
first = tickets.min_by(&:minute)
last = tickets.max_by(&:minute)
puts "door open #{last.minute - first.minute} minutes"
Output:
presented: 9
19:02 friday h2 r 4 s11 stalls admit stalls row 4 seat 11
19:04 friday h2 r 0 s 0 stalls unseated
19:07 thursday h2 r 6 s 3 stalls wrong night
19:11 friday h1 r 2 s 8 stalls wrong house
19:13 friday h2 r12 s 2 circle admit circle row 12 seat 2
19:15 friday h2 r 4 s11 stalls admit stalls row 4 seat 11
19:22 friday h2 r 9 s 1 circle wrong area
19:30 friday h2 r 5 s 0 stalls admit stalls row 5 seat 0
19:35 thursday h2 r 7 s 4 stalls wrong night
admitted 4 refused 5
refusals by reason:
wrong night 2
unseated 1
wrong area 1
wrong house 1
door open 33 minutes
Every row becomes a Ticket with six named fields, and the clock is normalised on the way in: 1902 becomes 1142 minutes past midnight, which makes "how long was the door open" a subtraction instead of a special case. format("%02d:%02d", t.minute / 60, t.minute % 60) puts it back for display, and both halves rely on integer division being integer division. verdict is the usher's sequence written out, refusals first, and it hands back a short string rather than a symbol or a boolean because that same string is both the message printed beside the ticket and the key the report tallies.
area_for is worth a second look, because it is a case with no else and it exists specifically to hand back nil. That nil means "this house has no such row", which is a genuinely different fact from "the row exists but the printed area is wrong", and the two are separated by the order of the next two guards: return "unseated" if seated.nil? comes first, so by the time the area comparison runs, seated is known to be a real area name. It is the same silent nil Technical Depth warned about, used deliberately, and safe only because the very next line tests for it.
The report uses Hash.new(0) so that the first refusal of a kind can be incremented without being created first, and it sorts with [-n, reason] rather than by count alone. That second element is not decoration. Four of the five refusals happen to occur once each, and with only -n as the key their printed order would follow whatever order they happened to be inserted in, so a quiet change to the ticket data would reorder a report that nobody expected to change.
Now the honest part. The seat number is never validated against anything at all, and the output shows it: the 19:30 ticket was admitted to row 5 seat 0, and the report counts that as one of four successful admissions. Only the row is checked, because area_for is the only thing resembling a house plan, and a real one would give the seat range for each row. Worse, nothing in the program notices that 19:02 and 19:15 were both sent to row 4 seat 11; the door book double-seats two patrons and calls it two admissions, which is the exact failure the book exists to prevent. There is a third flaw in the same family: v.start_with?("admit") is the test for "was this person let in", so the decision is stringly typed, and a future verdict of "admin override" would be counted as an admission by accident. Beyond those, to_i turns an unreadable row number into 0, which then reports as unseated and blames the customer for a corrupt file.
Common Mistakes
- Assuming that zero, the empty string or the empty array are falsy. A guard written
return unless countnever fires for a count of0, andif nameis satisfied by"". The same mistake in reverse is writingif flag == true, which rejects every truthy value that is not literallytrue. Ask the precise question:zero?,empty?,nil?, or a bareif flag.
- Using
andororwhere&&or||belongs. Their precedence is below assignment, soadmitted = verdict(t) or "unknown"assigns the verdict and then evaluates theorfor nothing, leavingadmittedasnilwhen the call returnednil. The parentheses Ruby inserts are not the ones you read.
- Attaching an
elseto anunless, or negating inside its condition.unless a != btakes two passes to read and gets misread on the third.unlessearns its keep only for a single condition that reads as plain English; everything else should be anif.
- Writing
=where==was meant.if area = "circle"assigns and then tests a non-empty string, so it is always true and it silently overwritesarea. Ruby warns about this with a literal on the right when run with-w, and says nothing at all when the right side is a variable.
- Typing
else ifinstead ofelsif. Ruby reads that as anelsecontaining a whole newif, which now needs its ownend. Either you get a syntax error pointing at the bottom of the file, a long way from the mistake, or the code parses and the branches nest in a shape you did not intend.
- Expecting
whento mean==. It calls===on thewhenvalue with the subject as the argument, which is whywhen Integerandwhen 1..10work at all. Reversing it does not work:case Integercompared againstwhen 7tests7 === Integerand quietly fails. The subject goes aftercase, always.
- Chaining past a safe navigation. In
usher&.name.upcase, the&.guards only the call toname; ifusherisnilthe expression becomesnil.upcaseand raises. Guard every link,usher&.name&.upcase, or restructure so the nil is handled once at the top.
- Trusting a
fetchdefault or||=to supply a boolean.fetch(key, 3)answers a missing key, not a key whose stored value isnil, so it returnsnilfor{ "k" => nil }. Andflag ||= trueoverwrites a deliberatefalse, becausefalseis not admitted. Wherefalseis a real setting, testkey?ornil?and assign from there.
- Letting a conditional hand back
nilfor an input nobody thought about. Anifwith noelse, or acasewith noelse, evaluates tonilwhen nothing matched, and if that is the last expression in a method the method returnsnilto a caller with no idea why. Either handle every case or put araisein theelseso the gap announces itself where it happens.
Best Practices
- Put the refusals at the top as guard clauses and let the success case sit unindented at the bottom, so a new check can be added without moving the real work further right.
- Reserve
unlessfor one plainly worded negation, and never give it anelseor a compound condition. - Use
&&and||when you want a value, treatandandoras control flow for short scripts, and keep either of them away from an assignment. - Prefer
caseto a run of three or moreelsifclauses, and use ranges, classes and lambdas aswhenvalues rather than converting everything to a boolean by hand. - Ask the precise question --
nil?,empty?,zero?,key?-- whenever absent, empty and zero are different facts, and use&.for one link you know may be nil rather than as a chain of hope. - Let conditionals be expressions: assign the result of the whole
iforcaseonce, instead of repeating an assignment inside every branch. - Give
caseanelse, even if thatelseonly raises, so that an unhandled subject reports itself at the point of the decision rather than as anilthree frames away. - Run new code once with
ruby -w; the warning about=in a conditional and the warning about an unreachable clause are both real bugs, every time.
Practice Exercises
- Predict The Door: Write down, before running anything, whether each of these is admitted by an
if:nil,false,0,0.0,""," ",[],{},:no,"false",-1,Float::NAN. Then run a loop that prints the truth. For every one you got wrong, write the precise predicate you should have used instead of a bare truth test.
- Flatten It: Take the
nestedmethod from Technical Depth and write your own flattened version without looking atflat. Then prove they agree by running both over at least six tickets, including a ticket that is missing the:housekey entirely, and print the two answers side by side. Explain what the missing key does and why it does not raise.
- Absent, Off, Or Unset: Build
config = { "retries" => nil, "verbose" => false }and print what each ofconfig["x"],config.fetch("x", 9),config.fetch("verbose", true),config["verbose"] || trueandconfig.key?("x")gives you. Then write asetting(config, key, default)helper that returns the stored value when the key is present, even when that value isfalseornil, and the default only when it is genuinely absent.
- Close The Door Properly: Fix the three flaws named above in
door_book.rb. Add a house plan giving the valid seat range for each row and refuse a seat outside it; detect a seat sold twice and refuse the later ticket with its own reason; add anunreadable ticketverdict for a row or seat that was not a number, so a corrupt file no longer reports asunseated; and replacestart_with?("admit")with a verdict object or symbol so that the admission test no longer depends on the wording of a message.