Ruby: Case Testing Against Arrays of Values

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 *truckable_countries
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
 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>