Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

i have a string variable which can only contain 6 different values. I want to check if it contains one of the first 4 values or one of the 2 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

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

like image 471
simonszu Avatar asked Jul 08 '13 12:07

simonszu


2 Answers

You could use include?:

if ['val1', 'val2', 'val3', 'val4'].include?(string)
like image 156
Dylan Markow Avatar answered Oct 14 '22 03:10

Dylan Markow


case string
when *%w[val1 val2 val3 val4]
  ...
else
  ...
end
like image 35
sawa Avatar answered Oct 14 '22 02:10

sawa