How is the following code giving an o/p of [0,2,4,6,8,10,12,14,16,18]
nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"
How is the following code giving an o/p of [0,2,4,6,8,10,12,14,16,18]
nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"
I believe the idea here is that e
represents each "number"
passed as the argument in your {}
block, populating it the multiple of 2
in an array, and you end up manipulating it by passing an argument. see more details there http://ruby-doc.org/core-2.2.1/Array.html
>> new_array = Array.new(10)
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
>> new_array = Array.new(10) { |e| e * 2 }
=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>> new_array = Array.new(10) { |e| e }
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The index value is what gets piped into the block. The return value from the block gets placed into the array at that index.