tags:

views:

94

answers:

3

This is more a question of semantics than anything else.

I'd like to check if a variable is either one of two values. The easiest way of doing this would be:

if var == "foo" || var == "bar"
# or
if var == 3     || var == 5

But this doesn't feel very DRY to me. I know I can use String.match(), but that doesn't work for non-string variables and is three times slower.

Is there a better way of checking a variable against two values?

+8  A: 

Put all values into an array and then it should be easy.

%w[foo bar].include?('foo') # => true

[3,5].include?(3) # => true
bryantsai
Missing the if statement... if(%w[foo bar].include?(var))
Sam Post
Yeah, I realized I could do this almost as soon as I posted the question. Thanks!
vonconrad
+1  A: 

You could do:

%W(foo bar baz).include? var

Or:

[3, 5].include? var
Brian Campbell
+4  A: 

The case statement seems to do what you want.

case var
  when "foo", "bar" then case1()
end

case var
  when 3, 5 then case2()
end

The array-based methods seem likely to be slower than this.

Aidan Cully
case notation just wraps around using `#===` for each when statement, so this will be the same as `if ["foo", "bar"] === var then case1(); elsif [3,5] === var then case2(); end`
rampion
I tried to test the speed of this vs. equivalent `.include?` method, and `case` was slightly faster. Not enough to make a compelling argument, though.
Aidan Cully
My problem with this approach that it feels clunkier than the one-line `if [1,2].include?(1)`. I agree that `case` works very well as a replacement for multiple if and elsif statements, but not for something simple like this.
vonconrad