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

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

4 thoughts on “Ruby: Case Testing Against Arrays of Values

  1. Oded

    Thanks for this insight, I wasn’t aware of this option when I came looking for something to make my when clauses easier on the eyes.

    Currently I’m using it like this:

    when *%w(one two three four)

    I wish ruby had fall through switch cases…


Leave a Reply

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