0

I have an array such as

['a','b','c','d','e','f']

I'm looking to create an array of each sequential pair

[['a','b'], ['c','d'], ['e','f']]

I know this is a simple question, but I am not sure how to phrase it to search for the answer and I've been searching for a while. Please point me in the right direction to an older answer and my apologies for the newbieness of the question.

CJ Jean
  • 971
  • 1
  • 8
  • 10

1 Answers1

6
%w[a b c d e f].each_slice(2).to_a
#=> [['a', 'b'], ['c', 'd'], ['e', 'f']]

Note: in most cases, you won't need to convert the result to an array. Enumerable#each_slice is an iterator method like #each, you can pass it a block or if you don't, it will return an Enumerator, which is Enumerable and supports pretty much all the methods you would want from an Array.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653