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.

1
  • 2
    arr.each_slice(2).entries Commented Jul 2, 2017 at 22:49

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.