Hi --

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

> greetings, David. how nice it is!
>
>> 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]]
>
> quick question. (sorry, i am still screwed up.)
> will the yieldee ( = the block ) 's 2nd parameter be nil at the end of
> the case of odd number as above ?

Yes:

   [1,2,3,4,5,6,7].in_slices_of(2).map {|x,y| [x,y]}
    => [[1, 2], [3, 4], [5, 6], [7, nil]]

I don't think there's much choice.  (You could of course just catch
each inner array in one variable.)


David

-- 
David A. Black
dblack / wobblini.net