tags:

views:

61

answers:

2

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]y = [[a, b], [c, d]]

A: 
Hash[*[:a, :b, :c, :d]].to_a
floatless
Clever, but it does not preserve the order.
jleedev
It does (at least in Ruby 1.9.2dev).
floatless
Fascinating! http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/
jleedev
It also fails if there happens to be a duplicate key. `Hash[*[:a,:b,:c,:d,:a,:e]]`
Chubas
+5  A: 
y = x.each_slice(2).to_a

irb(main):001:0> [0,1,2,3,4,5].each_slice(2).to_a
=> [[0, 1], [2, 3], [4, 5]]
deinst
Thanks! I missed this method somehow.
Ivan Kataitsev