1

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?

1 Answer 1

5
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
Sign up to request clarification or add additional context in comments.

5 Comments

i am not sure if the questioner wanted to replace it in place ( in the array_main), but if so, then (s)he should use the destructive method map!, instead of map
@Zippie: Since which verion of Ruby is map! available, that I managed to miss it?
@Zippie: That map! is a funny name anyway, who has ever heard of mappings destroying their domain? It's real fun to try e = array_main.map! and then manually call e.next several times, and see how array_main is destroyed. Is this useful, or what?
Why is map! funny? It's an in-place mutation of the original array, which is useful if you don't want to create a new variable. It's potentially faster too, because no extra variable allocation should be happening. And, it's been part of Ruby for a long time.
@theTinMan: No, no, I don't mean that map! itself is funny, it is an amazing piece of functionality, that I regret is not available also for Hash. Just the name is funny, map with bang!!! Modifies the functional domain!!! That sounds like a math joke, it makes me laugh. Functional programming flowing in reverse!!! a = 1, 2, 3; e = a.map!; e.each { 42 }. (I'm drunk again.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.