46
有没有更好的方式来写:使用.include检查数组中的多个项目? - 红宝石初学者
if myarray.include? 'val1' ||
myarray.include? 'val2' ||
myarray.include? 'val3' ||
myarray.include? 'val4'
有没有更好的方式来写:使用.include检查数组中的多个项目? - 红宝石初学者
if myarray.include? 'val1' ||
myarray.include? 'val2' ||
myarray.include? 'val3' ||
myarray.include? 'val4'
使用set交叉口(Array#:&):
(myarray & ["val1", "val2", "val3", "val4"]).present?
您也可以循环(any?
将停止在第一次出现):
myarray.any? { |x| ["val1", "val2", "val3", "val4"].include?(x) }
对小阵列来说没问题,在一般情况下,你最好有O(1)谓词:
values = ["val1", "val2", "val3", "val4"].to_set
myarray.any? { |x| values.include?(x) }
使用Ruby> = 2.1,使用Set#intersect:
myarray.to_set.intersect?(values.to_set)
是有什么简单的阅读这样'如果myarray.include? ['val1','val2','val3']'如果不是,那么我想你的答案似乎是最好的。 – Hopstream
@Hopstream,增加了另一个实现与任何? – tokland
为什么使用否定形式?为什么不使用'(self&other).any?'而不是'!(self&other).empty?' –