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

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"}]

Leave a Comment