tags:

views:

88

answers:

4

I am basically looking for a prettier way to write:

do_something() if my_string == 'first' | my_string == 'second' | my_string == 'third'

Any ideas?

+5  A: 

The most common solution is to use Array#include?:

do_something if %w(first second third).include? my_string
Adrian
Awww, I kept looking for methods of the form my_string.in %w(first second third). I just need to reverse my perspective :) Thanks.
hundredwatt
You can really take your pick on the Enumerable methods, detect is Enumerable#detect is another nice one http://apidock.com/ruby/Enumerable/detect but it returns nil, not false if there is no value found
Jed Schneider
A: 
do_something() if ['first', 'second', 'third'].include? my_string
mykhal
A: 

do_something if my_string =~ /^(first|second|third)$/

Wayne Conrad
A: 

If you worry about efficiency and/or legibility, I'd recommend first building a list of special values with a good constant name explaining why these are special, and then using it like:

require 'set'
SPECIAL_VALUES = Set["first", "second", "third"]

def foo(my_string)
  do_something if SPECIAL_VALUES.include?(my_string)
end

In case there are differences in the way you want to handle the cases for "first", "second", etc..., then you can use a Hash instead of a Set.

Marc-André Lafortune