returning a modified array after comparing in ruby

Viewed 54

I have two arrays:

arr1 = [10,20,7]
arr2=[]

On the first array I am performing a division calculation similar to this:

 arr1.each do |i|
    res = i.to_f/2.0
   arr2.push(res.round)
 end 

This will return arr2 = [5,10,4]

From the output array again I want to compare with the first array i.e [10,20,7]

If the output array arr2 contains value from any of the value from arr1

I want to replace that value with value/2.0

I am able to do a comparison like below:

arr2.any?{|x| arr1.include?(x)}

But I want to replace that value after comparing. How can I do that?

1 Answers

As any? only returns a boolean by evaluating the condition in the block, it doesn't allow you to do any modification to the receiver.

You can do that by using map and return a new object, where the values present in arr2 and in arr1 are divided by 2.0:

arr2.map do |x|
  match = arr1.find { |y| x == y }
  match ? match / 2.0 : x
end
# [5, 5.0, 4]

find allows you to look for elements in the receiver that match the condition in the block and return the first of them if exists, otherwise nil.

Related