psharma
psharma

Reputation: 1289

How do I replace repetitive elements in an array matching another array?

I have two arrays:

array_main = [23432, 3434, 312, 32432] 
array_second = [23432, 312]

I want to replace the elements in array_main with 0 matching the elements of array_second, so the output should look like:

array_main = [0, 3434, 0, 32432]

How do I do it?

Upvotes: 1

Views: 78

Answers (1)

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

array_main.map { |e| array_second.include?( e ) ? 0 : e }

And if you drop that requirement about replacing with 0, you can simply write

array_main - array_second

Upvotes: 5

Related Questions