views:

86

answers:

3

Newbie Ruby question:

I'm currently writing:

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

is there a neater way of doing this?

+13  A: 

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!

jerhinesmith
In Ruby, you should really reach for anchors \A and \Z unless you're sure the string contains zero newlines.
glenn jackman
@glennjackman, Would that be `/\Avalue(A|B|C)\Z/` instead?
jerhinesmith
yes, indeed. It does impair the readability unfortunately.
glenn jackman
+3  A: 

How 'bout

if %w(valueA valueB valueC).include?(mystring)
  # do something
end
oenli
A: 

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
Tim Snowhite