From: grzegorz.jakubiak@...
Date: 2020-10-30T10:07:54+00:00
Subject: [ruby-core:100666] [Ruby master Feature#17277] Make Enumerator#with_index yield row and col indices for Matrix

Issue #17277 has been updated by greggzst (Grzegorz Jakubiak).


sawa (Tsuyoshi Sawada) wrote in #note-7:
> I think the current behaviour is natural. You cannot play around with `with_index` since its receiver is `Enumerator`, not `Matrix`, and the information as a matrix is already gone.
> 
> You can retrieve the row and column indices easily from the flattened indices:
> 
> ```ruby
> matrix.each.with_index{|e, index| p index.divmod(matrix.column_size)}
> [0, 0]
> [0, 1]
> [0, 2]
> [0, 3]
> [1, 0]
> [1, 1]
> [1, 2]
> [1, 3]
> [2, 0]
> [2, 1]
> [2, 2]
> [2, 3]
> ```

I get that but it means performing divmod calculation every time one needs to work row and col indices out. Couldn���t we maybe return a subclass of Enumerator that implements proper with_index for Matrix?



----------------------------------------
Feature #17277: Make Enumerator#with_index yield row and col indices for Matrix
https://bugs.ruby-lang.org/issues/17277#change-88307

* Author: greggzst (Grzegorz Jakubiak)
* Status: Assigned
* Priority: Normal
* Assignee: marcandre (Marc-Andre Lafortune)
----------------------------------------
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, 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 indices.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>