In Ruby, why does Array.new(size, object) create an array consisting of multiple references to the same object?

前端 未结 3 1847
陌清茗
陌清茗 2020-11-30 14:19

As mentioned in this answer, Array.new(size, object) creates an array with size references to the same object.

hash =          


        
3条回答
  •  没有蜡笔的小新
    2020-11-30 14:55

    Because that's what the documentation says it does. Note that Hash.new is only being called once, so of course there's only one Hash

    If you want to create a new object for every element in the array, pass a block to the Array.new method, and that block will be called for each new element:

    >> a = Array.new(2) { Hash.new }
    => [{}, {}]
    >> a[0]['cat'] = 'feline'
    => "feline"
    >> a
    => [{"cat"=>"feline"}, {}]
    >> a[1]['cat'] = 'Felix'
    => "Felix"
    >> a
    => [{"cat"=>"feline"}, {"cat"=>"Felix"}]
    

提交回复
热议问题