From: Brian Candler Date: 2007-03-16T15:25:46+09:00 Subject: Re: Anyone playing with higher order messaging in ruby? On Thu, Mar 15, 2007 at 04:04:01AM +0900, Christoffer Lern? wrote: > For example, something that I often want to do is: > > array.each { |entry| entry.do_something(1, "a") } If do_something doesn't take any arguments then there's the hack which allows array.each(&:do_something) See http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html > If you know you're doing things like this a lot, there is an obvious > shortcut: > > class Array > > class Forwarder > def initialize(array) > @array = array > end > def method_missing(symbol, *args) > @array.each { |entry| entry.__send__(symbol, *args) } > end > end > > def each_do > Forwarder.new(self) > end > > end > > Now you can do: > > array.each_do.do_something(1, "a") or just: module Enumberable def each_do(meth, *args, &blk) each { |item| item.send(meth, *args, &blk) } end end array.each_do(:do_something, 1, "a") which has the advantage that do_something can take a block too, if you wish. B.