Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I say "if x == A or B or C" as succinctly as possible?

Tags:

ruby

I'm pretty sure ruby has an idiom for that.

I just have too many places in my code where I say

if (x == A) || (x == B) || (x ==C)
  do_something
else
  do_something_else
end

I know I also could do

case x
when A, B, C
   do_something
else
   do_something_else
end

but I prefer using if else if there's a nice idiom to make it more succinct.

like image 412
jpw Avatar asked Jul 03 '11 22:07

jpw


2 Answers

One way would be [A, B, C].include?(x)

like image 63
Dogbert Avatar answered Sep 27 '22 20:09

Dogbert


You can tidy up your case statement a bit more like this

case x
when A, B, C then do_something
else do_something_else
end

or if it is a repeating pattern, roll it into a method on Object

class Object
  def is_one_of?(*inputs)
    inputs.include?(self)
  end
end

then use it as

if x.is_one_of?(A, B, C)
  do_something
else
  do_something_else
end
like image 30
edgerunner Avatar answered Sep 27 '22 21:09

edgerunner