Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

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]]
like image 555
Roja Buck Avatar asked Jul 19 '10 21:07

Roja Buck


1 Answers

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.

like image 106
sepp2k Avatar answered Sep 29 '22 21:09

sepp2k