在Ruby中,为什么Array.new(大小,对象)创建包含多个引用的同一个对象的数组? [英] In Ruby, why does Array.new(size, object) create an array consisting of multiple references to the same object?

查看:148
本文介绍了在Ruby中,为什么Array.new(大小,对象)创建包含多个引用的同一个对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为<一提到href=\"http://stackoverflow.com/questions/4601652/ruby-array-creation-array-new-vs/4601727#4601727\">this回答, Array.new(大小,对象)创建一个具有相同的尺寸引用数组对象

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

为什么红宝石做到这一点,而不是做一个 DUP 克隆 的对象

推荐答案

由于这正是文档说它。需要注意的是 Hash.new 只被调用一次,当然因此只有一个哈希

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(大小,对象)创建包含多个引用的同一个对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆