Enumerable hacks

Generalising the two methods in
http://www.rubygarden.org/ruby?StandardClassExtensions/Enumerable

Not as cool as using method_missing, but a lot more extensible :slight_smile:

class Module

add a _with_index to iterators

def with_index(*args)
args.each {|meth|
module_eval <<-here
def #{meth.to_s}_with_index(*args, &block)
i = -1
send(:#{meth},*args) {|n|
i = i+1
block.call(n,i)
}
end
here
}
end

add a β€˜f’ method called with a method rather than a block

def _f(*args)
args.each {|meth|
module_eval <<-here
def #{meth}f(*args)
#{meth} {|obj| obj.send(*args)}
end
here
}
end
end

module Enumerable
with_index :map
_f :map
end

a = %w(all your base are belong to us)
p a.map_with_index {|n,i| β€œ(#{i}) #{n}”}
p a.mapf(:reverse)

Martin DeMello wrote:

Generalising the two methods in
http://www.rubygarden.org/ruby?StandardClassExtensions/Enumerable

Not as cool as using method_missing, but a lot more extensible :slight_smile:

It’s pretty cool, and probably more efficient. Some minor optimizations:

  def #{meth.to_s}_with_index(*args, &block)
     def #{meth}_with_index(*args)
      block.call(n,i)
         yield(n,i)   # yield is more efficient than making a Proc