Jump to content

Creating an Array: Difference between revisions

m (→‎Tcl: fix lang tag)
Line 818:
<lang ruby>a = [[0] * 3] * 2] # [[0, 0, 0], [0, 0, 0]]
a[0][0] = 1
putsp a.inspect # [[1, 0, 0], [1, 0, 0]]</lang>
So both inner arrays refer to the same object
<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:
<lang ruby>a = Array.new(2) {Array.new(3) {0}}
putsp a.inspect # [[0, 0, 0], [0, 0, 0]]
a[1][1] = 1
putsp a.inspect # [[0, 0, 0], [0, 1, 0]]</lang>
 
You can also create a sequential array from a range using the 'splat' operator:
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.