Project

General

Profile

Feature #17277

Updated by sawa (Tsuyoshi Sawada) about 4 years ago

Given a matrix: 

 ```ruby 
 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`: 

 ```ruby 
 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: 

 ```ruby 
 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, seems to iterate over the elements of the internal array, which does not look right: 

 ```ruby 
 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 col indices.

Back