Array Initialization: Difference between revisions

add Ruby
(add Ruby)
Line 422:
myArray.append([0] * width)
</lang>
 
=={{header|Ruby}}==
{{trans|Python}}
 
Ruby exhibits from some the same symptoms of references to objects as the Python solution
<lang ruby>a = ['an', 'apple', 'a', 'day', '...']
b = %w(an apple a day ...)
a == b # => true
 
width, height = 3, 2
 
a = [0] * width # OK => [0, 0, 0]
a[0] = 1
a # => [1, 0, 0]
 
a = [[0] * width] * height # => [[0, 0, 0], [0, 0, 0]]
a[0][0] = 1
a # => [[1, 0, 0], [1, 0, 0]] -- oops
a[0] == a[1] # => true -- as we expect
a[0].equal? a[1] # => true -- oops, same object
 
 
a = height.times.collect {width.times.collect{0}} # => [[0, 0, 0], [0, 0, 0]]
a[0].equal? a[1] # => false -- phew!
a[0][0] = 1
a # => [[1, 0, 0], [0, 0, 0]] -- OK</lang>
 
=={{header|Smalltalk}}==
Anonymous user