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.
One way would be [A, B, C].include?(x)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With