jay
jay

Reputation: 319

Is there a cleaner way to write this kind of Ruby conditional?

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

Upvotes: 1

Views: 122

Answers (2)

mu is too short
mu is too short

Reputation: 434665

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.

Upvotes: 1

maerics
maerics

Reputation: 156434

puts var1 if %w(hi bye well hello).include? var1

Upvotes: 6

Related Questions