A case statement selects one execution path by testing a value against ordered alternatives. It begins with a case expression, continues through when clauses, may include else, and ends with end. At most one when clause wins; if none matches, else handles the value. section 6.1.3
Branching on user input
case answer when "yes" puts "Good-bye!" exit when "no" puts "OK, we'll continue" else puts "That's an unknown answer -- I'm assuming you meant 'no'" end A when clause can contain multiple alternatives: when "y", "yes" acts like an or and runs the same branch for either input. section 6.1.3
Ruby defines a match through the case-equality method ===. Conceptually, each when object receives === with the case value as its argument. Thus case answer when "yes" behaves like if "yes" === answer. This message-sending model lets objects define their own case behavior. section 6.1.3
Custom matching with ===
A Ticket class can define === to compare venues. With case ticket1, when ticket2, and when ticket3, the matching ticket object determines whether its venue equals ticket1's venue; ticket3 wins when both tickets refer to Town Hall. section 6.1.3
Case statements also support these forms:
- Omit the case expression and use when conditions directly, which provides a readable alternative to an if/elsif chain. section 6.1.3
- Use the case expression as a value, such as passing puts the string selected by the winning when clause. section 6.1.3
- Use regular expressions as when objects, as in when /^y/, to match input beginning with y. section 1.4.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
Explore a complete interactive example that repeatedly asks whether to exit, handles yes, no, and unknown answers, and combines case with recursion. section 6.1.3








