Comparing a variable with two different values ​​in Ruby

This is more a matter of semantics than anything else.

I want to check if a variable is one of two values. The easiest way to do this:

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

But for me this is not very EXISTING. I know that I can use String.match() , but this does not work for non-string variables and is three times slower.

Is there a better way to check a variable for two values?

+4
source share
3 answers

Put all the values ​​in an array and then it will be easy.

 %w[foo bar].include?('foo') # => true [3,5].include?(3) # => true 
+14
source

The case seems to do what you want.

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

Array-based methods are likely to be slower than that.

+5
source

You can do:

 %W(foo bar baz).include? var 

Or:

 [3, 5].include? var 
+1
source

All Articles