Project

General

Profile

Actions

Feature #17277

closed

Make Enumerator#with_index yield row and col indices for Matrix

Feature #17277: Make Enumerator#with_index yield row and col indices for Matrix

Added by greggzst (Grzegorz Jakubiak) about 5 years ago. Updated almost 5 years ago.

Status:
Closed
Target version:
-
[ruby-core:100471]

Description

Given a matrix:

matrix = Matrix[[0,2,3,4], [6,7,8,9], [1,4,5,8]] 

You could get the row and col indices of a matrix using Matrix#each_with_index:

matrix .each_with_index { |e, row, col| p [row, col] } [0, 0] [0, 1] [0, 2] [0, 3] [1, 0] [1, 1] [1, 2] [1, 3] [2, 0] [2, 1] [2, 2] [2, 3] 

You can chain it with other enumerators and access indices within them:

matrix .each_with_index .filter_map { |e, row, col| [row, col] if e % 4 == 0} # => [[0, 0], [0, 3], [1, 2], [2, 1], [2, 3]] 

Meanwhile, with_index after Matrix#each returns flattened indices, not row or column indices, which does not look right:

matrix .each.with_index { |e, index| p index } 0 1 2 3 4 5 6 7 8 9 10 11 

I feel we should override with_index for Matrix so it returns row and column indices.

Actions

Also available in: PDF Atom