Issue #14585 has been updated by sawa (Tsuyoshi Sawada).


I think you have the wrong data structure in the first place. I think you either should have an array of arrays of length two, or a hash.

----------------------------------------
Feature #14585: Array#each_pair
https://bugs.ruby-lang.org/issues/14585#change-70857

* Author: iamvery (Jay Hayes)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
# Abstract

I propose we add the method #each_pair to Array. It would effectively be a name for the common case each_cons(2).

# Background

A few times now, I have wanted to do something pairwise on an array of values. One example where this has come up is to display a list of values of consecutive ranges:

```
arr = [1,2,3,4]
arr.each_cons(2) do |(a,b)|
  puts "#{a}-#{b}"
end
# 1-2
# 2-3
# 3-4
```

# Proposal

I see the value of Array#each_pair in being able to more clearly express a common use case where you wish do something with each overlapping pair of values in an array. It also mirrors Hash's similarly named interface well.

# Implementation

The implementation could be as simple as aliasing each_cons(2):

```
class Array
  def each_pair
    each_cons(2)
  end
end
```

# Evaluation

 One drawback I see is that it may not be clear that Array#each_pair groups overlapping pairs vs. chunking elements, e.g. [1, 2, 3, 4] => [[1, 2], [2, 3], [3, 4]] vs. [[1, 2], [3, 4]]. This could be addressed with an argument, but it may also be a feature killer, e.g. [1,2,3].each_pair(overlapping: true).

# Discussion

[empty]

# Summary

Overall I'd say that having an interface like this, named well, might make it easier to figure out how to access overlapping pairs of array elements. I've ending up needing to do this a few times now and both times I struggled to remember each_cons(2) is the way to do it as the name wasn't very intention revealing to me. (my brain kept saying "chunk").

This is my first feature suggestion. I'm looking forward to your feedback :). Thanks for all you do! <3



-- 
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>