Creating an Array: Difference between revisions
Content added Content deleted
(→{{header|Tcl}}: migrate from Array Initialization) |
(→{{header|Ruby}}: migrate from Array Initialization) |
||
Line 774: | Line 774: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
⚫ | |||
<lang ruby> my_array = Array.new |
<lang ruby> my_array = Array.new |
||
another_array = []</lang> |
|||
⚫ | |||
Arrays of strings: |
|||
<lang>x = ['an', 'array', 'of', 'strings'] |
|||
y = %w{another array of strings without the punctuation}</lang> |
|||
⚫ | |||
<lang ruby> my_array = 1, 2, 3, 4, 5 |
|||
⚫ | |||
my_array = [ 1, 2, 3, 4, 5 ] |
|||
array = [ |
array = [ |
||
Line 787: | Line 790: | ||
[2, 2, 2, 2, 2, 2], |
[2, 2, 2, 2, 2, 2], |
||
[3, 3, 3, 3, 3, 3] |
[3, 3, 3, 3, 3, 3] |
||
] |
]</lang> |
||
You would call the array by this code. This will call the 4th element on the second list |
|||
<lang ruby>array[1][3]</lang> |
|||
We have to be careful when creating multidimensional arrays: |
|||
⚫ | |||
<lang ruby>a = [[0] * 3] * 2] # [[0, 0, 0], [0, 0, 0]] |
|||
⚫ | |||
a[0][0] = 1 |
|||
puts 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: |
|||
⚫ | |||
puts a.inspect # [[0, 0, 0], [0, 0, 0]] |
|||
a[1][1] = 1 |
|||
puts a.inspect # [[0, 0, 0], [0, 1, 0]]</lang> |
|||
⚫ | |||
⚫ | |||
# or use the .to_a method for Ranges |
# or use the .to_a method for Ranges |
||
array = (0..3).to_a |
array = (0..3).to_a #=> [0,1,2,3]</lang> |
||
#=> [0,1,2,3] |
|||
# This lets us create the above programmatically: |
|||
⚫ | |||
# or use the .map (.collect which is the same) method for Ranges directly |
|||
# note also that arrays of length 6 with a default element are created using Array.new |
|||
⚫ | |||
# you can also do the first map using Array.new too |
|||
⚫ | |||
This lets us create [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]] programmatically: |
|||
⚫ | |||
⚫ | |||
array = Array.new(4) {|i| Array.new(6,i)}</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |