Using set intersections (Array#:&):
(myarray & ["val1", "val2", "val3", "val4"]).present?
You can also loop (any?
will stop at the first occurrence):
myarray.any? { |x| ["val1", "val2", "val3", "val4"].include?(x) }
That's ok for small arrays, in the general case you better have O(1) predicates:
values = ["val1", "val2", "val3", "val4"].to_set
myarray.any? { |x| values.include?(x) }
With Ruby >= 2.1, use Set#intersect:
myarray.to_set.intersect?(values.to_set)
Create your own reusable method:
class String
def include_any?(array)
array.any? {|i| self.include? i}
end
end
"a string with many words".include_any?(["a", "string"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With