Matrix on ruby

2023-07-29 ruby

Need to be cafeful on using * to define muitl dimensions array.

irb> matrix = [[0] * 3] * 2
=> [[0, 0, 0], [0, 0, 0]]
irb> matrix[1][0] = 1
=> 1
irb> matrix
=> [[1, 0, 0], [1, 0, 0]]  # not the expected result!

Use block to generate independent objects.

irb> matrix = Array.new(2) { Array.new(3,0) }
=> [[0, 0, 0], [0, 0, 0]]
irb> matrix[1][0] = 1
=> 1
irb> matrix
=> [[0, 0, 0], [1, 0, 0]]  # Perfect!