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]]
Stefan
  • 109,145
  • 14
  • 143
  • 218
Ivan Kataitsev
  • 537
  • 1
  • 4
  • 8

2 Answers2

89

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]]
Stefan
  • 109,145
  • 14
  • 143
  • 218
deinst
  • 18,402
  • 3
  • 47
  • 45
4
Hash[*[:a, :b, :c, :d]].to_a
Daniel O'Hara
  • 13,307
  • 3
  • 46
  • 68