Cascading message sends

I’m a nuby, so I’m not sure if this is the Ruby Way, but you can try:

class Object
def repeat_call(meth, *args)
args.each { |arg| self.send(meth, *arg) }
end
end

ary = []
ary.repeat_call(:push, 1, [[2, 3]], 4)
p ary #=> [1, [2, 3],
4]

s = " he llo 8765 world "
s.repeat_call(‘gsub!’, [/\s/, ‘’], [/\d/, ‘’])
p s #=> “helloworld”

···

-----Original Message-----
From: Paul MG [mailto:paulmg@digitalbrain.com]
Sent: Monday, 2 February 2004 4:50 AM
To: ruby-talk ML
Subject: Re: cascading message sends

“Mark J. Reed” markjreed@mail.com wrote in message
news:20040131211520.GA15084@mulan.thereeds.org

I just wanted to point out that you can do this without any
special syntax as long as the methods involved return `self’ -
which many do, including Array#push.

It’s lucky that in Ruby Array#push and Array#<< do return self; unlike
Smalltalk’s Collection>>add: anItem which returns anItem (I believe).

However as I said in the PS to my original post, I was curious about
what can be done in Ruby in the general case.

Aside: The things people have been able to do in suggesting ways to get
this behaviour have really illustrated to me the power of the
language: there seems to be something almost LISP-like in the way you
can extend nearly everything about the language, eg adding methods to
Object, Kernel, etc. Very impressive. I think Python is cute (and i have
to admit to preferring syntactically-significant-indentation to ruby’s
"end" keyword) but Ruby seems to clearly trounce it for sheer power.

Thanks for everyone’s thoughts!

cheers:)
Paul