Baham's Blog

Above all else, guard your heart.

Ruby Multidimensional Arrays

Today, when I use Two-dimensional array with ruby.

Like:

1
2
3
4
arr=[]
arr2=[]
3.times  { arr2 << "_" }
3.time   {arr << arr2}

And when I change the arr[1][1] to "-"

It will show:

1
2
3
 _ - _
 _ - _
 _ - _

But what I want is :

1
2
3
_ _ _
_ - _
_ _ _

I did not know why this happened. So I search it by search engineer.

And I found a differen thing in ruby.

If you want to output right image. Like above.

You need init your array like this:

1
arr=[[" _"," _"," _"],[" _"," _"," _"],[" _"," _"," _"]]

The Reason

When you use te first way to create a two-dimensinol array.

The sub array point to the same object arr2.

1
2
3
4
5
6
7
8
9
Array.new(3, Array.new(3,0)).each{|i|p i.object_id}
-616182288
-616182288
-616182288

[[0, 0, 0], [0, 0, 0], [0, 0, 0]].each{|i|p i.object_id}
-616198918
-616198928
-616198938

Reference Article:

Lvguoning Blog




The Original Link: http://baham.github.io/05_06_ruby-multidimensional-arrays.html
If you want to reprint it, please do under the CC BY-NC-SA 4.0

Comments