Easily compare a variable with multiple values

I often forget this simple little trick for comparing multiple values against a single variable.

Instead of

var = 2
if var == 1 || var == 2 || var == 3
  puts "yes"
end
#=> "yes"

You can do the following

var = 2
if [1,2,3].include?(var)
  puts "yes"
end
#=> "yes"

Comments (2)

NickJuly 16th, 2009 at 11:52

Thanks for the reminder, I’d forgotten this technique.

PS. are you the Andrew Timberlake that sold me a Cape Epic entry a few years back?

Andrew TimberlakeJuly 16th, 2009 at 11:57

That would be me :-)