From: "Christoffer Lernö" Date: 2007-03-16T20:20:28+09:00 Subject: Re: Anyone playing with higher order messaging in ruby? On Mar 16, 2007, at 07:25 , Brian Candler wrote: >> 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. Well, actually you might want to pass around the result of each_do to something else, this is why I believe that in most cases the former version is preferable. Consider a chat server where @clients = [connection1, connection2...] assuming each connection has a method like "broadcast_chat", the code looks like this: @clients.each_do.broadcast_chat(incoming_chat) I like it because it feels clear what is happening and that this is the same as @clients.each { |c| c.broadcast_chat(incoming_chat) } Here @cliente.each_do(:broadcast_chat, incoming_chat) is not as obvious when it comes to detemining what is the action and what is the data.