Filter to exclude elements from array
Your code works for me.
As for "better way", you could 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 it is more idiomatic, but Ruby's for i in collection
loops are implemented in terms of collection.each { |i| }
. A method with a block is almost always a better alternative.
Array#excluding (Rails 6+)
If you are using Rails (or a standalone ActiveSupport), starting from version 6, there is a Array#excluding method which returns a copy of the array excluding the specified elements.
["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"]
[ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ]) # => [ [ 0, 1 ] ]
So, your example can be rewritten as follows:
total = ['alpha', 'bravo', 'charlie', 'delta', 'echo']
hide = ['charlie', 'echo']
pick = total.excluding(hide)
# => ['alpha', 'bravo', 'delta']
Ruby lets you use public instance methods on 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']
For more information check rubydoc Array. It's likely that you'll find exactly what you need there.