Ruby — Case and when expressions
A Ruby case expression selects the first matching when clause and returns its value. Comma-separated alternatives can share one clause.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
case 2
when 2 then puts "two"
else puts "other"
end
two
Route several event states to one action
Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. For string alternatives Ruby's case comparison matches the string content. An else clause gives an unknown event an explicit result.
A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.
Run the example
Use Ruby 2.6 or later. Run these commands from the directory containing the example.
ruby lesson.rb
def route(state)
case state
when 'queued', 'retry' then 'pending'
when 'sent' then 'done'
else 'review'
end
end
%w[queued retry sent unknown].each { |state| puts route(state) }
pending pending done review
Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.
Try it yourself
What should an unrecognized state such as paused produce?
Check your answer
It produces review. Add an explicit case when the application defines how to handle that state.