Creating an Array: Difference between revisions
Content added Content deleted
m (remove Ruby) |
|||
Line 773: | Line 773: | ||
5 => "c" |
5 => "c" |
||
=={{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> |
|||
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 brackets |
|||
<lang ruby> my_array = 1, 2, 3, 4, 5 |
|||
my_array = [ 1, 2, 3, 4, 5 ] |
|||
array = [ |
|||
[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> |
|||
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: |
|||
<lang ruby>a = Array.new(2) {Array.new(3) {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> |
|||
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: |
|||
<lang ruby> array = [*0..3].map {|i| [i] * 6} |
|||
array = 4.times.map {|i| Array.new(6,i)} |
|||
array = Array.new(4) {|i| Array.new(6,i)}</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |