42

What is the easiest way to convert a ruby array to an array of consecutive pairs of its elements?

I mean:

x = [:a, :b, :c, :d]

Expected result:

y #=> [[:a, :b], [:c, :d]]

2 Answers 2

90

Use Enumerable#each_slice:

y = x.each_slice(2).to_a
#=> [[:a, :b], [:c, :d]]

[0, 1, 2, 3, 4, 5].each_slice(2).to_a
#=> [[0, 1], [2, 3], [4, 5]]
Sign up to request clarification or add additional context in comments.

Comments

4
Hash[*[:a, :b, :c, :d]].to_a

4 Comments

Clever, but it does not preserve the order.
It does (at least in Ruby 1.9.2dev).
It also fails if there happens to be a duplicate key. Hash[*[:a,:b,:c,:d,:a,:e]]
Also fails if length of array is not divisible by 2. - Hash[*[1,2,3]].to_a fails [1,2,3].each_slice(2).to_a doesn't

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.