在 Ruby 中,为什么 Array.new(size, object) 创建一个包含对同一对象的多个引用的数组? [英] In Ruby, why does Array.new(size, object) create an array consisting of multiple references to the same object?
问题描述
如这个答案中所述,Array.new(size, object)
创建一个数组,其中 size
引用相同的 object
.
As mentioned in this answer, Array.new(size, object)
creates an array with size
references to the same object
.
hash = Hash.new
a = Array.new(2, hash)
a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"},{"cat"=>"feline"}]
a[1]['cat'] = 'Felix'
a # => [{"cat"=>"Felix"},{"cat"=>"Felix"}]
为什么 Ruby 会这样做,而不是对 object
进行 dup
或 clone
?
Why does Ruby do this, rather than doing a dup
or clone
of object
?
推荐答案
因为这就是 文档 说确实如此.注意 Hash.new
只被调用一次,所以当然只有一个 Hash
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
如果要为数组中的每个元素创建一个新对象,请将一个块传递给 Array.new
方法,该块将为每个新元素调用:
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"}]
这篇关于在 Ruby 中,为什么 Array.new(size, object) 创建一个包含对同一对象的多个引用的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!