liveBook · Manning

When clause

As explained in The Well-Grounded Rubyist, Fourth Edition

A when clause is a branch of a Ruby case statement containing match conditions and code to execute when a condition matches.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines matching through `===`, permits multiple conditions per clause, and demonstrates custom matching.
Examples
Uses yes/no input, comma-separated alternatives, and a Ticket class whose `===` method matches venues.
What you can do after
Apply Ruby `case` syntax to route values to a matching branch, with `else` handling unmatched input.
How it connects
Connects case statements to `===`, if/elsif conditionals, and user-input handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.