I am basically looking for a prettier way to write:
do_something() if my_string == 'first' | my_string == 'second' | my_string == 'third'
Any ideas?
I am basically looking for a prettier way to write:
do_something() if my_string == 'first' | my_string == 'second' | my_string == 'third'
Any ideas?
The most common solution is to use Array#include?
:
do_something if %w(first second third).include? my_string
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
.