0

If I have 2 arrays, for example a = [1, 2, 3, 4, 5] and b = [4, 7, 9, 1]

and I want to use a method to change elements of the first one. For example

a.map {|x| x.to_s}

but I don't want to change elements that are the same as in the array b. In this case my desire result would be

a = [1, "2", "3", 4, "5"]

1 and 4 are still integers, because the array b has this elements.

So how can I implement this task?

arrays and methods are used just for example to explain what I mean.

2 Answers 2

2

you can achieve this with a simple ternary operator inside your map block to either add the respective element as is or as a string depending on whether the second array contains an element with that value:

a.map { |x| (b.include? x) ? x : x.to_s }
Sign up to request clarification or add additional context in comments.

Comments

1
a.map!{|e| b.include?(e) ? e : e.to_s}

1 Comment

...and if the arrays are large, first convert b to a set.

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.