Ruby Matrix
Using the Matrix class in place of 2d arrays

When I need to use a grid-like data structure, I pick a 2 dimensional array:
arr = [
[1, 2, 3],
[2, 3, 4],
[5, 6, 7]
]
And so, whenever I need to iterate over all the values, I need a nested enumerator or I could flatten the array and then iterate.
array.each_with_index do |row, row_idx|
row.each_with_index do |cell, col_idx|
# do work
end
end
The Matrix class helps here.
require 'matrix'
m = Matrix[
[1, 2, 3],
[2, 3, 4],
[5, 6, 7]
]
A difference between Array, where we look up row / column with arr[row][col]
, we use m[row, col]
with Matrix.
Because Matrix mixes in Enumerable, it exposes all the wonderful methods from that module, but each
goes element by element and each_with_index
gives us the cell value and the row and column position.
m.each_with_index { |cell, row, col| #...
And transforms with map
are nice
m.map { |cell| cell * 2 }
# => Matrix[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
Member discussion