Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Ruby's map method work in this case?

I got the mistake when I want to add doubled values to an array:

arr = [1,2,3]

def my_mistake(arr)
  result = Array.new
  arr.map { |element| result << element * 2 }
end
#=> [[2, 4, 6], [2, 4, 6], [2, 4, 6]]

def solution(arr)
  arr.map { |element| element * 2 }
end
#=> [2,4,6]

However, come back to my mistake and the definition of map method in Ruby.

Invokes the given block once for each element of self. Creates a new array containing the values returned by the block.

I think my_mistake method has to return [[2], [2, 4], [2, 4, 6]] but it doesn't.

Everyone can explain this case for me ?

like image 709
Cuong Vu Avatar asked Oct 05 '14 10:10

Cuong Vu


1 Answers

The resulting array will contain three occurrences of the same reference to the same array, as result is the result of the expression result << element * 2. So the result of the map is (kind of) [result, result, result]. These all point to the same content, which is the content of result at the end of the process ([2, 4, 6]).

What you expected would be achieved if you clone the array at each point, so that every resulting element would point to a different array, and each addition would not affect the previously computed arrays:

arr.map { |element| (result << element * 2).clone }
=> [[2], [2, 4], [2, 4, 6]]
like image 146
Patrice Gahide Avatar answered Sep 28 '22 04:09

Patrice Gahide