Python 有非常优雅的语法来根据多种模式检查一个值。
2 in [1,2,4] #=> True
6 in [1,2,4] #=> False
Ruby 版本中的顺序感觉不对:
[1,2,4].include?(2)
我知道 include?
比 2.included_in?([1,2,4])
更面向对象,但我还是不喜欢它. Ruby 甚至有 in
关键字,但它似乎只用于构建 for i in [1,2,4]
,而不用于成员资格测试。
另一种方式是这样的:
(case 2 when 1,2,4 then true end)
相当冗长,但允许模式测试:
(case file_name when "README", /\.txt\z/ then true end)
仍然不是很可读。
我是不是偶然错过了一些非常漂亮的方法?
最佳答案
正如@deceze 所说,您可以实现自己的:
class Object
def in(ar)
ar.include? self
end
end
irb(main):013:0> 's'.in ['a', 'b', 'c']
=> false
irb(main):014:0> 's'.in ['a', 'b', 'c', 's']
=> true
irb(main):015:0> 5.0.in [3.2, 5.0, 1.2]
=> true
irb(main):016:0> 4.0.in [3.2, 5.0, 1.2]
=> false
关于[一、二、三]中的 foo 等同于 Ruby?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3369500/