Array Initialization: Difference between revisions
Content added Content deleted
m (remove Tcl) |
m (remove Ruby) |
||
Line 437: | Line 437: | ||
myArray.append([0] * width) |
myArray.append([0] * width) |
||
</lang> |
</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 = Array.new(height) { Array.new(width) {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|Slate}}== |
=={{header|Slate}}== |