Dan Diebolt wrote:
> Is is possible to redefine each so that each_with_index behavior can be 
> acheived with an extra parameter to the block each is called with? In 
> other words, how do you redefine each so that instead of using this 
> construct:

> ======
> This is my attempt to redefine Array#each but it does not work:
> ??
> class Array
> ?? alias :old_each :each
> ?? def each(&block)
> ?????? puts "arity=#{block.arity}"
> ?????? case block.arity
> ?????? when 1
> ?????????? old_each &block
> ?????? when 2
> ?????????? each_with_index &block
> ?????? end
> ?? end
> end
> ??
> a=[1,2,3]
> ??

I'm not exactly sure why your code does not work.  It seems that 
each_with_index and each depend on each other in ways which you are not 
capturing with your redefined each.  But you can roll your own index 
tracking:

  def each(&block)
    i = 0
    arity = block.arity
    old_each do |curr|
      case arity
        when 1: yield curr
        else yield curr, i
      end
      i+=1
    end
  end

-- 
Posted via http://www.ruby-forum.com/.