To create a Two Dimensional Array in Ruby, you can use arrays within an array.
In this example,
matrix
with dimensions 3x3.matrix = Array.new(3) { Array.new(3) }
matrix.each_with_index do |row, i|
row.each_with_index do |_, j|
matrix[i][j] = i + j
end
end
puts matrix.inspect
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
In this example,
matrix
with dimensions 2x2.matrix = Array.new(2) { Array.new(2) }
matrix.each_with_index do |row, i|
row.each_with_index do |_, j|
matrix[i][j] = "Row #{i + 1}, Column #{j + 1}"
end
end
puts matrix.inspect
[["Row 1, Column 1", "Row 1, Column 2"], ["Row 2, Column 1", "Row 2, Column 2"]]
In this tutorial, we learned How to create a Two Dimensional Array in Ruby language with well detailed examples.