开发者

Is this a bug in the Array.fill method in Ruby? [duplicate]

开发者 https://www.devze.com 2023-01-08 12:09 出处:网络
This quest开发者_运维问答ion already has an answer here: Arrays misbehaving (1 answer) Closed 6 years ago.
This quest开发者_运维问答ion already has an answer here: Arrays misbehaving (1 answer) Closed 6 years ago.

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.


It is correct, Array.new(array) returns a new array created with size copies of obj (that is, size references to the same obj)

0

精彩评论

暂无评论...
验证码 换一张
取 消