Check for multiple array elements with .include? - Ruby newbie

Is there a better way to write this:

if myarray.include? 'val1' || myarray.include? 'val2' || myarray.include? 'val3' || myarray.include? 'val4' 
+45
ruby ruby-on-rails
Nov 06 2018-11-11T00:
source share
1 answer

Using Intersection Set ( Array #: & ):

 (myarray & ["val1", "val2", "val3", "val4"]).present? 

You can also execute a loop ( any? Will stop on the first entry):

 myarray.any? { |x| ["val1", "val2", "val3", "val4"].include?(x) } 

This is normal for small arrays, in general it is better to 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) 
+77
Nov 06 '11 at 10:10
source share



All Articles