Anonymous user
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}}==
<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 bracks
array = [
Line 787 ⟶ 790:
[2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 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:
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
array = (0..3).to_a #=> [0,1,2,3]</lang>
array = [*0..3].map {|i| [i] * 6}▼
array = (0..3).map {|i| Array.new(6,i)}▼
▲ array = Array.new(4) {|i| Array.new(6,i)}
array = Array.new(4) {|i| Array.new(6,i)}</lang>
=={{header|Scala}}==
|