60

Is there a better way to write this:

if myarray.include? 'val1' ||
   myarray.include? 'val2' ||
   myarray.include? 'val3' ||
   myarray.include? 'val4'

2 Answers 2

109

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)
Sign up to request clarification or add additional context in comments.

13 Comments

is there something simpler to read like this if myarray.include? ['val1', 'val2', 'val3'] If not, then I guess your answer seems best.
@Hopstream, added another implementation with any?
why use the negative form ? why not just use (self & other).any? instead of !(self & other).empty?
@m_x: good point, usually any? is used with a block, but it makes perfect sense without. Edited. edit but what if nil/false are values in the arrays? any will fail...
interesting. looking at the sources of any? and empty?, from a performance point of view, you're indeed right to use the negative form (empty? just checks the length of the C array, while any? involves a more complex process because of the absent block). I learned something today.
|
5

Create your own reusable method:

class String
  def include_any?(array)
    array.any? {|i| self.include? i}
  end
end

Usage

"a string with many words".include_any?(["a", "string"])

1 Comment

thx a lot, it's the good answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.