有没有更好的方法来写这个:
if myarray.include? 'val1' ||
myarray.include? 'val2' ||
myarray.include? 'val3' ||
myarray.include? 'val4'
答案 0 :(得分:93)
使用set intersectionctions(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)
答案 1 :(得分:3)
创建自己的可重用方法:
class String
def include_any?(array)
array.any? {|i| self.include? i}
end
end
"a string with many words".include_any?(["a", "string"])