5

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?

3 Answers 3

17

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

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

[3,5].include?(3) # => true
Sign up to request clarification or add additional context in comments.

2 Comments

Missing the if statement... if(%w[foo bar].include?(var))
Yeah, I realized I could do this almost as soon as I posted the question. Thanks!
5

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.

3 Comments

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
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.
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.
1

You could do:

%W(foo bar baz).include? var

Or:

[3, 5].include? var

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.