Why does Array#each return an array with the same elements?

后端 未结 4 1858
名媛妹妹
名媛妹妹 2021-02-18 14:21

I\'m learning the details of how each works in ruby, and I tried out the following line of code:

p [1,2,3,4,5].each { |element| el }
4条回答
  •  野性不改
    2021-02-18 14:40

    Array#each returns the [array] object it was invoked upon: the result of the block is discarded. Thus if there are no icky side-effects to the original array then nothing will have changed.

    Perhaps you mean to use map?

    p [1,2,3,4,5].map { |i| i*i }
    

提交回复
热议问题