How to check if a string is one of several different values?

I have a string variable that can only contain 6 different values. I want to check if it contains one of the first four values ​​or one of the two second values.

Is there a more elegant way than this:

if string.eql? 'val1' || string.eql? 'val2' || string.eql? 'val3' || string.eql? 'val4' ... elsif string.eql? 'val5' || string.eql? 'val6' ... end 

Perhaps something like if string is in ['val1', 'val2', 'val3', 'val4'] ?

+4
source share
3 answers

Can you use include? :

 if ['val1', 'val2', 'val3', 'val4'].include?(string) 
+15
source
 case string when *%w[val1 val2 val3 val4] ... else ... end 
+1
source

Array#index

Returns the index of the first object in ary, so the object is == to obj. Returns zero if no match is found.

 puts "something" if ['val1', 'val2', 'val3', 'val4'].index("val1") # >> something 
0
source

Source: https://habr.com/ru/post/1490278/


All Articles