Reputation: 1303
Is there an easy way to iterate through 2 arrays and find any element values that are exactly the same in both arrays and populate it into a new array?
For example:
arr_a = ["a","b","c","d"]
arr_b = ["123","456","b","d","c"]
The array I want to create would be:
new_arr = ["b","c","d"]
I tried this:
another_arr = [*arr_a, *arr_b] #combines the 2 arrays
another_arr.select { |e| another_arr.count(e) >1 }.uniq #then find all dupes
but I don't know how to push the results to an array.
Is this the right way of going about it? Are there any ideas how push the results to an array?
Upvotes: 0
Views: 89
Reputation: 176
What you are attempting to do is a Set Intersection, which can be achieved in Ruby using the &
operator.
arr_a = ["a","b","c","d"]
arr_b = ["123","456","b","d","c"]
new_array = arr_a & arr_b
Read more about this in "ary & other_ary".
Upvotes: 5
Reputation: 30056
You're looking for intersection of two sets. This is way simpler:
arr_a & arr_b
Upvotes: 1