Viktor Danilov Viktor Danilov - 2 months ago 16
Ruby Question

Analog for '&' with duplicates

From Ruby documentation:


ary & other_ary → new_ary

Set Intersection —
Returns a new array containing elements common to the two arrays,
excluding any duplicates. The order is preserved from the original
array.


But is there a built-in method to do the same thing including duplicates?

Test case:

ary = [2, 7, 3, 7]
other_ary = [7, 2, 7, 4]
new_ary == [2, 7, 7]

Answer

Maybe something like this ?

ary.select{ |a| other_ary.include? a }
#=> [2, 7, 7]