Why does ruby not have cascade messages?

“A cascade sends multiple messages to the same receiver”

Hi, In smalltalk this is possible.

As far as I know ruby has no direct way to support cascading method
calls.

object.method1().method2() # would not work as method1() would not
return self

Then I was thinking, perhaps with a different syntax:

object.(method1|method2)

Could return an array. Or:

object…(method1|method2)

(Hmm, not good, … is the Range operator … but you get the idea.)

Smalltalk has something like this:

“If a series of messages are sent to the same receiver, they can also be
written as a cascade with individual messages separated by semicolons:”

Smalltalk Code:

Window new
label: ‘Hello’;
open

“This rewrite of the earlier example as a single expression avoids the
need to store the new window in a temporary variable. According to the
usual precedence rules, the unary message “new” is sent first, and then
“label:” and “open” are sent to the answer of “new”.”

This all works without one having to create a variable where Window.new
is stored.

In Pseudo-Ruby this could look like:

Window.new.label(‘Hello’).open # but of course this would not work

On Sat, Aug 24, 2013 at 11:39 PM, Marc H. [email protected]
wrote:

Then I was thinking, perhaps with a different syntax:
Smalltalk Code:
This all works without one having to create a variable where Window.new
is stored.

In Pseudo-Ruby this could look like:

Window.new.label(‘Hello’).open # but of course this would not work

Window.new.instance_eval do
label ‘Hello’
open
end

will work. Ruby/Tk uses a similar technique by allowing to pass a block
to
the constructor of objects which will be invoked via #instance_eval.
Examples:

http://rubylearning.com/satishtalim/ruby_tk_tutorial.html

Cheers

robert

You often see this in Ruby referred to as method chaining, with but it
is
not a given
The given class/methods have to be designed to work that way
I see Wikipedia has a short description that mentions Smalltalk’s
cascading
in comparison:
http://en.wikipedia.org/wiki/Method_chaining#Ruby

I was thinking the String class would be a good example, but it’s
methods
often return a new string, which may not be what you want
The ‘!’ methods seem to return self, except when the method does not
modify
the string, in which case it returns nil, so is fragile for chaining

On 25/08/2013, at 9:39 AM, Marc H. [email protected] wrote:

This all works without one having to create a variable where Window.new
is stored.

In Pseudo-Ruby this could look like:

Window.new.label(‘Hello’).open # but of course this would not work

Try ‘tap’

Window.new.tap do |w|
w.label(‘Hello’)
w.open
end

Henry