On Sun, 10 Dec 2000, Dave Thomas wrote:

> "Ben Tilly" <ben_tilly / hotmail.com> writes:
> 
> > >I guess my confusion comes from the intent of the code: why would you
> > >ever _ask_ for elements outside the bounds of the array?
> > >
> > I have felt the convenience in Perl.  For instance:
> > 
> >   while (my @group = splice(@list, 0, 10)) {
> >     # Do something with the group of entries
> >   }
> > 
> > The point being to push down to the language all of the
> > logic about where the boundaries of the array are.  This
> > snippet for implementing paging logic would be much longer
> > if I had to concern myself with logic about finding the
> > boundary of the array.  Instead I just know that it will
> > exit correctly, and might sometimes give me fewer elements.
> 
> I guess in this circumstance I'd be looking for an extension to #pop
> or #unshift
> 
>    arr.pop(10)  -> newArray
> 
> where newArray would be nil if arr was empty, or up to 10 elements
> otherwise.


Somewhat in this general vein, I'd been yearning for the ability to do
this:

  a = (0...10) .to_a
  a.in_slices_of(3) # => [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]


The yearning was satisfied when I wrote a method to do it :-) The
relevance here is that it's another example of how nice it can be not
to have to worry about the array boundaries.  

The method is:

   class Array
     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

in case anyone's interested in it, and/or in commenting on it.


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav