Check for multiple items in array using .include? -- Ruby Beginner

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


Is there a better way to write this:

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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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)

Solution 2 - Ruby on-Rails

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"])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHopstreamView Question on Stackoverflow
Solution 1 - Ruby on-RailstoklandView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJeremy LynchView Answer on Stackoverflow