Farrel Lifson wrote:
> On 08/01/07, Sam Kong <sam.s.kong / gmail.com> wrote:
> > Hello,
> >
> > What's the best way to do the following?
> >
> > [1,2,3,4,5,6,7,8,9] => [[1,2,3],[4,5,6],[7,8,9]]
> >
> > I want to transform the array into an array of arrays with fixed number
> > of elements.
> > I think there should be a method but I can't find it.
> >
> > I can iterate the elements using a counter to divide but it's so
> > boring.
> >
> > Thanks in advance.
> >
> > Sam
> >
> >
> >
>
> requre 'enumerator'
>
> [1,2,3,4,5,6,7,8,9].enum_slice(3).inject([]){|array,slice| array << slice}
>
> Farrel

requre 'enumerator'
[ 1, 2, 3, 4, 5, 6, 7, 8 ].enum_slice(3).to_aj


Without "require":
[ 1, 2, 3, 4, 5, 6, 7, 8 ].inject([[]]){|a,e|
  a << [] if a.last.size==3;  a.last << e; a}