How to understand Ruby's .each and .map

后端 未结 5 568
予麋鹿
予麋鹿 2021-01-18 21:00

I am having trouble understanding the differences between map and each, and where and when to use them.

I read \"What does map do?\" and \

5条回答
  •  长情又很酷
    2021-01-18 21:36

    In the first case, map:

     z = [1,2,3].map {|x| x + 1}
    

    will take each element in the given array and perform the operation in the block and return a new array, so here it returns [2,3,4].

    .each executes the block for each of the elements in the array, and it will not change anything in the array, so here it performs x + 1, but it doesn't store it anywhere, hence in the second case it just returns the array.

    Now in the third example you posted, you are printing output in the block itself. Again, there is no change in the array itself.

提交回复
热议问题