Filter to exclude items from an array

Trying to filter some records from an array. This does not guarantee that they are in the main array, so I am testing iteration.

total = ['alpha', 'bravo', 'charlie', 'delta', 'echo'] hide = ['charlie', 'echo'] pick = [] for i in total if !hide.include?(i) puts i pick.push(i) end end puts pick 

This does not work. Is there a better way to provide such a filter?

+11
source share
3 answers

Ruby allows you to use public instance methods for two arrays to get their intersecting or exclusive elements:

 a1 = ['alpha', 'bravo', 'charlie', 'delta', 'echo'] a2 = ['charlie', 'echo'] puts a1 - a2 => ['alpha', 'bravo', 'delta'] puts a1 & a2 => ['charlie', 'echo'] 

Check out the Rubydoc Array for more information. It is likely that you will find exactly what you need there.

+20
source

Your code works for me. As for the "best way", you can use Array#reject :

 total = ['alpha', 'bravo', 'charlie', 'delta', 'echo'] hide = ['charlie', 'echo'] pick = total.reject do |i| hide.include?(i) end puts pick 

Not only is this more idiomatic, but Ruby for i in collection loops are implemented in terms of collection.each { |i| } collection.each { |i| } . A block method is almost always the best alternative.

+8
source

What about .select / reject ? Or a mutant version of .select! / reject! ?

Here are the docs .

Using:

 [0, 1, 2, 3].select { |x| x > 1 } # output: [2, 3] 

Or in your case:

 execluded = [0, 1] [0, 1, 2, 3].reject { |x| execluded.include?(x) } # output: [2, 3] 
+2
source

All Articles