My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a
the result of a is
[[1], [1], [1]]
in irb…
I don’t understand why.
I just wannt insert into a 1 into the third array of a.
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a
the result of a is
[[1], [1], [1]]
in irb…
I don’t understand why.
I just wannt insert into a 1 into the third array of a.
On 3 Jan 2008, at 11:21, Wu Ning wrote:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts athe result of a is
[[1], [1], [1]]
in irb…I don’t understand why.
Array.new will insert the second argument you give into the array (3
times since that’s what you’ve asked for). However it’s the same array
(You can see this quite easily if you do Array.new(3,Array.new).map {|
x| x.object_id}). So a is not an array containing 3 arrays, it’s an
array containing the same array 3 times.
a = Array.new(3) {[]}
should do the trick (since the block is called once for each element
of the array)
Fred
Wu Ning kirjoitti:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a
I suppose you wanted to type
irb(main):012:0> uber = [[], [], 3]
=> [[], [], 3]
Csmr
Wu Ning wrote:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts athe result of a is
[[1], [1], [1]]
in irb…I don’t understand why.
I just wannt insert into a 1 into the third array of a.
After a = Array.new(3,Array.new()), a is an array containing three
references to the same object. There is only one array, but it is
repeated three times.
Do
a = []; 3.times { a << [] }
and you’ll have three different arrays.
best,
Dan
Thanks,
I know what’s going on now,
Daniel L. wrote:
Wu Ning wrote:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts athe result of a is
[[1], [1], [1]]
in irb…I don’t understand why.
I just wannt insert into a 1 into the third array of a.After a = Array.new(3,Array.new()), a is an array containing three
references to the same object. There is only one array, but it is
repeated three times.Do
a = []; 3.times { a << [] }
and you’ll have three different arrays.best,
Dan
On Jan 3, 2008 1:11 PM, Wu Ning [email protected] wrote:
Thanks,
I know what’s going on now,
Good Ruby has however a syntax that will do what you intended in
the first place, see below please… and yes err
please do not top post unless you have a very good reason to do so in
which case I apologize for having mentioned it.Daniel L. wrote:
Wu Ning wrote:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a = Array.new(3){ [] }
a[2]<<1
puts a
[ [],[],[1] ]
HTH
Robert
–
http://ruby-smalltalk.blogspot.com/
Whereof one cannot speak, thereof one must be silent.
Ludwig Wittgenstein
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs