1

I'm trying to find out if there's a cleaner way to write something like this:

if var1 == "hi" || var1 == "bye" || var1 == "well" || var1 == "hello"
  puts var1
end

Basically, there's one variable and I want to find out if it's equal to one of several possible values.

I tried the following but it was invalid:

if var1 == ("hi" || "bye" || "well" || "hello")
  puts var1
end
jay
  • 329
  • 4
  • 10

2 Answers2

6
puts var1 if %w(hi bye well hello).include? var1
maerics
  • 151,642
  • 46
  • 269
  • 291
  • 1
    Wow, that is amazing! Thank you. For anybody that finds this question in the future, %w is difficult to type into search engines so here is a link to a related question about how to use them: http://stackoverflow.com/questions/4287503/where-in-the-ruby-language-is-q-w-etc-defined – jay Jan 12 '12 at 22:22
  • 1
    actually %w is not a key part of the solution, it's just another way to make arrays. "['hi', 'bye', 'well', 'hello'].include? var1" would do the same thing. – jrochkind Jan 13 '12 at 15:54
1

If the list is bigger and you're going to be checking it a lot, then you can save some time by using a Hash:

want = Hash[%w{hi bye well hello}.map { |s| [ s, true ] }]
puts var1 if(want[var1])

or a Set:

want = Set[*%w{hi bye well hello}] # Or want = %w{...}.to_set
puts var1 if want.include? var1

Building the Hash or Set is a one-time hit but checking the Hash will be a lot faster than scanning an Array with include?. The difference might be worth it if there are a lot of things to check or if you're checking over and over again.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 1
    Set[%w{hi bye well hello}] by writing this, the Set got only one value with is the array itself so the code is not working. Maybe %w{hi bye well hello}.to_set ? – oldergod Sep 04 '12 at 01:09
  • 1
    @oldergod: I think I left out a splat (`Set[*%w{...}]`) but `to_set` would serve just as well. Thanks for spotting that. – mu is too short Sep 04 '12 at 01:46