这是Ruby的Array.fill方法错误? [英] Is this a bug in the Array.fill method in Ruby?
本文介绍了这是Ruby的Array.fill方法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果这是即我误解,或者是一个错误吗?这样
A = Array.new(3 Array.new(3))
一[1] .fill伪('G')= GT; [[G,G,G],[G,G,G],[G,G,G]]
它不应该导致:
=> [零,零,零],[G,G,G],[零,零,零]
解决方案
Array.new(3 Array.new(3))
返回它包含相同的数组阵列的三倍。(换言之:恩pression Array.new(3)
被计算一次,并没有拷贝制作)
你可能想要的是 Array.new(3){Array.new(3)}
,其计算 Array.new(3)
三次,从而为您提供了三个独立的数组的数组。
Should this be the case i.e. I am misunderstanding, or is it a bug?
a = Array.new(3, Array.new(3))
a[1].fill('g')
=> [["g", "g", "g"], ["g", "g", "g"], ["g", "g", "g"]]
should it not result in:
=> [[nil, nil, nil], ["g", "g", "g"], [nil, nil, nil]]
解决方案
Array.new(3, Array.new(3))
returns an array which contains the same array three times (in other words: the expression Array.new(3)
is evaluated exactly once and no copies are made).
What you probably want is Array.new(3) { Array.new(3) }
, which evaluates Array.new(3)
three times and thus gives you an array of three independent arrays.
这篇关于这是Ruby的Array.fill方法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文