开发者

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

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
开发者_如何学Python

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


Other ways:

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 @edgerunner's solution, generalized

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜