2

Given the array: [1,2,3,4] I would like to receive an array back of [[1,2],[2,3],[3,4]].

Is there a one-liner or a method that does this?

Sixty4Bit
  • 12,852
  • 13
  • 48
  • 62
  • 2
    BTW it's not an array of all the pairs (i.e. 2-element combinations), it's an array with all consecutive pairs. – Marek Lipka Mar 05 '19 at 14:05
  • @MarekLipka Thank you for the clarification! – Sixty4Bit Mar 05 '19 at 14:14
  • By the way, it would help tremendously, what the problem is with the documentation of `Enumerable#each_cons` or `Enumerable` in general that prevented you from finding this method. That way, the Ruby developers can improve the documentation so that future developers don't have this problem. – Jörg W Mittag Mar 05 '19 at 14:50
  • @JörgWMittag the primary problem is that I didn't know the concept of "consecutive". Not a fault on anyone but my lack of experience. – Sixty4Bit Mar 05 '19 at 18:04

1 Answers1

2

You can use Enumerable#each_cons, passing 2 as argument:

[1, 2, 3, 4].each_cons(2).to_a
# [[1, 2], [2, 3], [3, 4]]

You need to use to_a there, because each_cons by itself returns an Enumerator object.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59