Creating an Array: Difference between revisions

→‎{{header|Ruby}}: migrate from Array Initialization
(→‎{{header|Tcl}}: migrate from Array Initialization)
(→‎{{header|Ruby}}: migrate from Array Initialization)
Line 774:
 
=={{header|Ruby}}==
# This is the most basic way to create an empty one-dimensional array in Ruby.:
 
<lang ruby> my_array = Array.new
another_array = []</lang>
# This is the most basic way to create an empty one-dimensional array in Ruby.
Arrays of strings:
<lang>x = ['an', 'array', 'of', 'strings']
y = %w{another array of strings without the punctuation}</lang>
 
# Ruby treats comma separated values on the right hand side of assignment as array. You could optionally surround the list with square bracksbrackets
<lang ruby> my_array = 1, 2, 3, 4, 5
# Ruby treats comma separated values on the right hand side of assignment as array. You could optionally surround the list with square bracks
# my_array = [ 1, 2, 3, 4, 5 ]
 
array = [
Line 787 ⟶ 790:
[2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 3]
]</lang>
# You would call the array by this code. This will call the 4th 1element on the second list
<lang ruby>array[1][3]</lang>
 
We have to be careful when creating multidimensional arrays:
# You can also create a sequential array from a range using the 'splat' operator:
<lang ruby>a = [[0] * 3] * 2] # [[0, 0, 0], [0, 0, 0]]
array = [*0..3]
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:
array<lang ruby>a = Array.new(42) {|i| Array.new(6,i3) {0}}
puts a.inspect # [[0, 0, 0], [0, 0, 0]]
a[1][1] = 1
puts a.inspect # [[0, 0, 0], [0, 1, 0]]</lang>
 
# You can also create a sequential array from a range using the 'splat' operator:
<lang ruby> array = [*0..3]
# or use the .to_a method for Ranges
array = (0..3).to_a #=> [0,1,2,3]</lang>
#=> [0,1,2,3]
# This lets us create the above programmatically:
array = [*0..3].map {|i| [i] * 6}
# 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
array = (0..3).map {|i| Array.new(6,i)}
# you can also do the first map using Array.new too
array = Array.new(4) {|i| Array.new(6,i)}
#=>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]]</lang> programmatically:
<lang ruby> array = [*0..3].map {|i| [i] * 6}
array = (04..3)times.map {|i| Array.new(6,i)}
array = Array.new(4) {|i| Array.new(6,i)}</lang>
 
=={{header|Scala}}==
Anonymous user