R – Comparing a variable against two different values in Ruby


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?

Best Solution

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

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

[3,5].include?(3) # => true
Related Question