From: William James Date: 2007-09-18T00:30:03+09:00 Subject: Re: group array elements in groups of two On Sep 17, 10:18 am, Emmanuel Oga wrote: > A better way to do this? : > > arr= [1, 2, 3, 4, 5, 6, 7, 8] > new= [] > while !arr.empty? > elem1, elem2= arr.pop, arr.pop > new << [elem2, elem1]; > end > new.reverse! > > new= [[1, 2], [3, 4], [5, 6], [7, 8]] This question has come up several times. require 'enumerator' ==>true [1, 2, 3, 4, 5, 6, 7, 8].enum_slice(2).to_a ==>[[1, 2], [3, 4], [5, 6], [7, 8]] Without 'require': f=nil ==>nil [1, 2, 3, 4, 5, 6, 7, 8].partition{f=!f}.transpose ==>[[1, 2], [3, 4], [5, 6], [7, 8]]