Hi --

On Mon, 29 Aug 2005, SHIGETOMI, Takuhiko wrote:

> dear guys,
>
> i am seeking a smart way to do ...
>
>   [ 1, 2, 3, 4, 5, 6, ... ]  =>  [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], ... ]
>
> especialy, the way hopefully will work safety when the source array's
> size is odd or zero.

I've got a method from long ago that might fit:

   class Array    # or do it as a module, or whatever
     def in_slices_of(n)
       res = []
       0.step(size - 1, n) do |i|
         s = slice(i...i + n)
         yield s if block_given?
         res.push s
       end
       res
     end
   end

   [1,2,3,4,5,6].in_slices_of(2)  # =>  [[1, 2], [3, 4], [5, 6]]
   [1,2,3,4,5,6].in_slices_of(3)  # => [[1, 2, 3], [4, 5, 6]]

It handles odd numbers by putting whatever's left over in its own
array:

   [1,2,3,4,5,6,7].in_slices_of(2)  # => [[1, 2], [3, 4], [5, 6], [7]]

(and note that it yields each slice too).

In 1.9 you can do:

   irb(main):015:0> [1,2,3,4,5,6].enum_slice(2).map {|x| x }
   => [[1, 2], [3, 4], [5, 6]]

which handles odd numbers the same way.  (I can't seem to get it to
return the desired result without doing the map operation.)


David

-- 
David A. Black
dblack / wobblini.net