On Thu, Dec 04, 2003 at 04:09:59AM +0900, David A. Black wrote:
> Just for fun:
> 
   module Enumerable
     def each_with_index(range=(0...size))
       range.each {|i| yield at(i),i}
     end
   end

A couple problems there.  First, the range from the original example
is 1..-1,  which won't work in the above code because treated as 
a standalone range, it's empty.  Only when applied to the context
of the array size does it make sense.

You can fix that like this:

   module Enumerable
     def each_with_index(range=(0...size))
	b, e, x = range.begin,range.end,range.exclude_end?
	if b < 0 || e < 0
	    b += size if b < 0
	    e += size if e < 0
	    range = Range.new(b,e,x)
	end
       range.each {|i| yield at(i),i}
     end
   end

Then this works:

irb(main):012:0> a=[0,1,-1]
=> [0, 1, -1]
irb(main):013:0> a.each_with_index(1..-1) do |x, i| puts "#{i}: #{x}" end
1: 1
2: -1
=> 1..2

Secondly, and less importantly, it not obvious to me that
array.each_with_index(range) should iterate over the given subrange
of the array.  What I would more expect is to iterate over all of
the array, but take the "index" values from the range instead of
using the real ones.  Which is a much sillier idea, but that's how
I read it.

-Mark