Did you know that a when clause in a Ruby case statement can test against each item in an array? If any item in the array matches the case statement’s comparison (target) value, the when clause will evaluate to true.
In the below example, :express_truck will be returned if country matches any of the truckable_countries.
truckable_countries = ['United States', 'Canada', 'Mexico'] ship_via = case country when *truckable_countries :express_truck else :supersonic_jet end
Why does this work?
In a when clause, the splat operator (*) functions similarly to how it as it does in a method call. In method invocation, splatting an array turns each array item into a parameter that’s passed to the method. In a when clause, splatting an array turns each array item into a comparison test associated with the clause.
The splat operator makes these three when clauses effectively equivalent:
when *['United States', 'Canada', 'Mexico']
when 'United States', 'Canada', 'Mexico'
Splat operator usage isn’t limited to just once in a when clause. As in method calls, splat can be used multiple times:
when *['United States', 'Canada'], 'Mexico', *other_countries