Friday 15 March 2013

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



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

i got error when want add together doubled values 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 error , definition of map method in ruby.

invokes given block 1 time each element of self. creates new array containing values returned block.

i think my_mistake method has homecoming [[2], [2, 4], [2, 4, 6]] doesn't.

everyone can explain case me ?

the resulting array contain 3 occurrences of same reference same array, result result of look result << element * 2. result of map (kind of) [result, result, result]. these point same content, content of result @ end of process ([2, 4, 6]).

what expected achieved if clone array @ each point, every resulting element point different array, , each add-on not impact computed arrays:

arr.map { |element| (result << element * 2).clone } => [[2], [2, 4], [2, 4, 6]]

ruby-on-rails ruby map

No comments:

Post a Comment