Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Is a string in a list of values

Newbie Ruby question:

I'm currently writing:

if mystring == "valueA" or mystring == "ValueB" or mystring == "ValueC"

is there a neater way of doing this?

like image 586
Mike Sutton Avatar asked Jan 21 '10 21:01

Mike Sutton


3 Answers

There are two ways:

RegEx:

if mystring =~ /^value(A|B|C)$/ # Use /\Avalue(A|B|C)\Z/ here instead 
   # do something               # to escape new lines
end

Or, more explicitly,

if ['valueA', 'valueB', 'valueC'].include?(mystring)
   # do something
end

Hope that helps!

like image 194
jerhinesmith Avatar answered Nov 08 '22 13:11

jerhinesmith


How 'bout

if %w(valueA valueB valueC).include?(mystring)
  # do something
end
like image 23
oenli Avatar answered Nov 08 '22 13:11

oenli


Presuming you'd want to extend this functionality with other match groups, you could also use case:

case mystring
when "valueA", "valueB", "valueC" then
 #do_something
when "value1", "value2", "value3" then
 #do_something else
else
 #do_a_third_thing
end
like image 1
Tim Snowhite Avatar answered Nov 08 '22 14:11

Tim Snowhite