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

后端 未结 4 1876
名媛妹妹
名媛妹妹 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:26

    Array#each

    The block form of Array#each returns the original Array object. You generally use #each when you want to do something with each element of an array inside the block. For example:

    [1, 2, 3, 4, 5].each { |element| puts element }
    

    This will print out each element, but returns the original array. You can verify this with:

    array = [1, 2, 3, 4, 5]
    array.each { |element| element }.object_id === array.object_id
    => true
    

    Array#map

    If you want to return a new array, you want to use Array#map or one of its synonyms. The block form of #map returns a different Array object. For example:

    array.object_id
    => 25659920
    array.map { |element| element }.object_id
    => 20546920
    array.map { |element| element }.object_id === array.object_id
    => false
    

    You will generally want to use #map when you want to operate on a modified version of the original array, while leaving the original unchanged.

    0 讨论(0)
  • 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 }
    
    0 讨论(0)
  • 2021-02-18 14:45

    All methods return something. Even if it's just a nil object, it returns something.

    It may as well return the original object rather than return nil.

    0 讨论(0)
  • 2021-02-18 14:45

    If you want, for some reason, to suppress the output (for example debugging in console) here is how you can achive that

      [1,2,3,4,5].each do |nr|
        puts nr.inspect
      end;nil
    
    0 讨论(0)
提交回复
热议问题