我通常使用[1, 2, 3].include? foo
成语。这没有什么本质上的错误,但为了便于阅读,能够写foo.is_in? [1, 2, 3]
会很好。核心库或标准库是否有一个可以执行此操作的方法?
答案 0 :(得分:1)
标准中没有这样的方法。自己实施:
class Object
def is_in? a
return a.include?(self)
end
end
请注意,在上面的代码中,我从不检查a的类型,因此如果没有为a定义include?
,则会出现错误。
答案 1 :(得分:0)
不完全按照您想要的方式,但您可以重写此
if [1, 2, 3].include? foo
do_this
else
do_that
end
到此:
case foo; when 1, 2, 3
do_this
else
do_that
end