How does the block form of Array#new work given “Array.new(10) { |e| e = e * 2 }”?

前端 未结 2 1310
夕颜
夕颜 2021-01-26 05:50

I am having trouble understanding the part inside the curly braces.

Array.new(10) { |e| e = e * 2 }
# => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]   
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-26 06:45

    Let's go over this in details:

    nums = Array.new(10)
    

    This creates a new array with 10 elements. For each array element it passes control to the block specified by:

    { |e| e = e * 2 }
    

    The |e| represents the element's index. The index is the position in the array. This starts at 0 and ends at 9 since the array has 10 elements. The second part multiplies the index by 2 and returns the value. This is because the e * 2, being the last statement in the block, is returned. The value returned is then applied to that element's value. So we end up with the following array:

    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    

    EDIT

    As mentioned by pjs and to avoid problems down the road, a simpler way to write the same code would be:

    Array.new(10) { |e| e * 2 }
    

提交回复
热议问题