我很确定ruby有这样的习惯用法。
我的代码中有太多地方我说
if (x == A) || (x == B) || (x ==C)
do_something
else
do_something_else
end
我知道我也可以做到
case x
when A, B, C
do_something
else
do_something_else
end
但我更喜欢使用if else
,如果有一个很好的习惯用法可以使它更简洁。
答案 0 :(得分:38)
一种方式是[A, B, C].include?(x)
答案 1 :(得分:5)
您可以稍微整理一下case
语句
case x
when A, B, C then do_something
else do_something_else
end
或如果是重复模式,请将其滚动到Object
class Object
def is_one_of?(*inputs)
inputs.include?(self)
end
end
然后将其用作
if x.is_one_of?(A, B, C)
do_something
else
do_something_else
end
答案 2 :(得分:0)
其他方式:
A,B,C = 1,2,3
arr = [A, B, C]
x = 2
y = 4
使用Array#&
[x] & arr == [x]
#=> true
[y] & arr == [y]
#=> false
使用Array#-
([x] - arr).empty?
#=> true
([y] - arr).empty?
#=> false
使用Array#|
arr | [x] == arr
#=> true
arr | [y] == arr
#=> false
arr.index(x)
#=> 1 (truthy)
arr.index(y)
#=> nil (falsy)
!!arr.index(x)
#=> true
!!arr.index(y)
#=> false
使用@ edgerunner的解决方案,通用
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