How can I say "if x == A or B or C" as concisely as possible?

I'm sure ruby โ€‹โ€‹has an idiom for this.

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 that I could do too

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

but I prefer to use if else if there is a nice idiom to make it more concise.

+7
source share
3 answers

You can tidy up your case 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, translate it into a method on Object

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

then use it like

 if x.is_one_of?(A, B, C) do_something else do_something_else end 
+5
source

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

+37
source

Other methods:

 A,B,C = 1,2,3 arr = [A, B, C] x = 2 y = 4 

Use Array # &

 [x] & arr == [x] #=> true [y] & arr == [y] #=> false 

Use Array # -

 ([x] - arr).empty? #=> true ([y] - arr).empty? #=> false 

Use Array # |

 arr | [x] == arr #=> true arr | [y] == arr #=> false 

Use Array # index

 arr.index(x) #=> 1 (truthy) arr.index(y) #=> nil (falsy) !!arr.index(x) #=> true !!arr.index(y) #=> false 

Use the @edgerunner generalized solution

 def present?(arr, o) case o when *arr puts "#{o} matched" else puts "#{o} not matched" end end present?(arr, x) # 2 matched present?(arr, y) # 4 not matched 
0
source

All Articles