A `when` clause pairs one or more match conditions with code to run inside a `case` statement. Ruby checks the clauses in turn; at most one match wins. section 6.1.3
A clause can:
- List several possible matches separated by commas; they act as alternatives. section 6.1.3
- Rely on `===` to determine whether a condition matches the `case` value. section 6.1.3
Listing 6.1 Interpreting user input with a case statement
def quit_or_not
print "Exit the program? (yes or no): "
answer = gets.chomp #1
case answer 1
when "yes" 2
puts "Good-bye!"
exit
when "no"
puts "OK, we'll continue"
else 3
puts "That's an unknown answer -- I'm assuming you meant 'no'"
end 4
puts "Continuing with program...."
quit_or_not 5
end
quit_or_not
See a yes/no prompt whose `when` clauses handle recognized answers and whose `else` clause handles other input. section 6.1.3
Listing 6.2 Implementing case statement behavior for the Ticket class
class Ticket
attr_accessor :venue, :date
def initialize(venue, date)
self.venue = venue
self.date = date
end
def ===(other_ticket) 1
self.venue == other_ticket.venue
end
end
ticket1 = Ticket.new("Town Hall", "07/08/25")
ticket2 = Ticket.new("Conference Center", "07/08/25")
ticket3 = Ticket.new("Town Hall", "08/09/25")
puts "ticket1 is for an event at: #{ticket1.venue}."
case ticket1
when ticket2 2
puts "Same location as ticket2!"
when ticket3 3
puts "Same location as ticket3!"
else
puts "No match."
end
A custom `===` method lets a `Ticket` object match another ticket by venue in a `when` clause. section 6.1.3
