From: "yermej@..." Date: 2007-07-11T22:19:56+09:00 Subject: Re: Repacking an array of arrays On Jul 9, 10:00 pm, Kaps Lok wrote: > Is there an elegant (maybe a one-liner) for repacking: > > [[1, 4, 7, 10, 13], [2, 5, 8, 11, 14], [3, 6, 9, 12, 15]] > > to? > > [[1, 4, 7], [10, 13, 2], [5, 8, 11], [14, 3, 6], [9, 12, 15]] > > So rather than having 3 arrays each with 5 elements, I get five arrays > of 3 elements each... > > the only way I can see to do this is by looping the array, and creating > new arrays. > > Any help would be much appreciated. Is the fact that it goes from 3 of 5 to 5 of 3 significant or do you always want to go to some number of 3 element arrays? E.g. would you ever have an array of 4 arrays of 6 elements and want to go to an array of 6 arrays with 4 elements each? If it's the first case, this will work, though there may be something more elegant: result = [] a.flatten.each_with_index {|x, i| i % 3 == 0 ? result << [x] : result[-1] << x} I suppose, if you need the second case, you could do something a little more general: result = [] a.flatten.each_with_index {|x, i| i % a.length == 0 ? result << [x] : result[-1] << x} Jeremy