Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby case statements with multiple variables

Ruby has a fairly powerful case..when..else construct for when you need to match criteria against a single variable. What is the "canonical" way to match criteria against multiple variables without simply nesting case statements?

Wrapping multiple variables in an array (like [x, y]) and matching against it isn't equivalent, because Ruby won't apply the magical case === operator to the elements of the array; the operator is only applied to the array itself.

I'm going to go ahead and respond with a community-wiki answer with a (defeated) stab at this question.

like image 576
ClosureCowboy Avatar asked Feb 01 '11 03:02

ClosureCowboy


1 Answers

You need to use an if..elsif..else, and ensure that the variables you want to match against appear on the right-hand side of the === operator (which is what case essentially does).

For example, if you want to match x and y against some criteria:

if (SomeType === x) && (1..10 === y)
  some_value
elsif (:some_symbol === x) && (11..20 === y)
  some_other_value
end
like image 132
2 revs, 2 users 89% Avatar answered Oct 20 '22 00:10

2 revs, 2 users 89%