Project

General

Profile

Feature #17277

Updated by sawa (Tsuyoshi Sawada) over 3 years ago

Given a matrix: Currently this code seems to be counting index based on the internal array of arrays and it's not correct for the matrix which should return row and col indices 

 ```ruby ``` 
 matrix = Matrix[[0,2,3,4], [6,7,8,9], [1,4,5,8]] [1,4,5,8]].each.with_index { |e, index| print "#{index} " } ; puts 
 0 1 2 3 4 5 6 7 8 9 10 11  
 => nil 
 ``` 

 You I'm aware of the fact that you could do following and you get the row and col indices of a matrix using `Matrix#each_with_index`: correct results: 

 ```ruby ``` 
 matrix 
 .each_with_index Matrix[[0,2,3,4], [6,7,8,9], [1,4,5,8]].each_with_index { |e, row, col| p [row, col] print "[#{row}, #{col}] " } ; puts 
 [0, 0] 
 [0, 1] 
 [0, 2] 
 [0, 3] 
 [1, 0] 
 [1, 1] 
 [1, 2] 
 [1, 3] 
 [2, 0] 
 [2, 1] 
 [2, 2] 
 [2, 3]  
 => nil 
 ``` 

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

 ```ruby them e.g. 
 matrix ``` 
 .each_with_index 
 .filter_map Matrix[[0,2,3,4], [6,7,8,9], [1,4,5,8]].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, `Matrix#each` 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 
 ``` 

 However, I feel we should override `with_index` for `Matrix` Matrix so it returns row and col indices.

Back