Creating an Array: Difference between revisions
Content added Content deleted
m (→Tcl: fix lang tag) |
(→Ruby) |
||
Line 818: | Line 818: | ||
<lang ruby>a = [[0] * 3] * 2] # [[0, 0, 0], [0, 0, 0]] |
<lang ruby>a = [[0] * 3] * 2] # [[0, 0, 0], [0, 0, 0]] |
||
a[0][0] = 1 |
a[0][0] = 1 |
||
p a # [[1, 0, 0], [1, 0, 0]]</lang> |
|||
So both inner arrays refer to the same object |
So both inner arrays refer to the same object |
||
<lang ruby>a[0].equal? a[1] # true</lang> |
<lang ruby>a[0].equal? a[1] # true</lang> |
||
The better way to create a multidimensional array is to use the form of <tt>Array.new</tt> that takes a block: |
The better way to create a multidimensional array is to use the form of <tt>Array.new</tt> that takes a block: |
||
<lang ruby>a = Array.new(2) {Array.new(3) {0}} |
<lang ruby>a = Array.new(2) {Array.new(3) {0}} |
||
p a # [[0, 0, 0], [0, 0, 0]] |
|||
a[1][1] = 1 |
a[1][1] = 1 |
||
p a # [[0, 0, 0], [0, 1, 0]]</lang> |
|||
You can also create a sequential array from a range using the 'splat' operator: |
You can also create a sequential array from a range using the 'splat' operator: |