How does the Ruby map method work in this case?

I got an error when I want to add double value values ​​to the 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]

But back to my mistake and the definition of the map method in Ruby.

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

It seems to me that the my_mistake method should return [[2], [2, 4], [2, 4, 6]], but it is not.

Can everyone explain this thing to me?

+4
source share
2 answers

, result result << element * 2. , map () [result, result, result]. , result ([2, 4, 6]).

, , , , , :

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

.map , < < . -, :

def my_mistake(arr)
  result = [] # '= []' is same like '= Array.new', look-up "literal constructors in Ruby"
  new_arr = [] # same like new_arr = Array.new
  until arr.empty?
    new_arr << arr.shift # we add each element of arr, one by one, starting from the beginning
    output << new_arr.map { |e| e * 2} # we calculate *2 for each element
  end
  return result
end
p my_mistake(arr) #=> [[2], [2, 4], [2, 4, 6]]

, , "p output" 6- :

def my_mistake(arr)
  output = []
  new_arr = []
  until arr.empty?
    new_arr << arr.shift
    output << new_arr.map { |e| e * 2}
    p output
  end
  return output
end

my_mistake(arr)

:

[[2]]
[[2], [2, 4]]
[[2], [2, 4], [2, 4, 6]]
0

All Articles