What does this construct mean?

J

Jim Freeze

* Casper said:
To be honest, that the following two lines
puts (3+4).abs
puts(3+4).abs
are semantically different *feels* very broken to me. My gut says that
this is a vector for confusion and the introduction of bugs.

I think it depends on what binding you prefer most.
Consider

method_that_returns_some_string(arg).upcase!

I think this does what one would expect. It is going
to upcase the returned string.
But, if it is written with a space after the method name

method_that_returns_some_string (arg).upcase!

you suggest that this should bind the same as if the space
were not present. That means that constructs like

sqrt (-2).abs

could not be written without an extra set of ()'s.
Doesn't this rule that ()'s after a method
are always bound to the method imply that ()'s
are essentially always needed, especially if
any argument uses parens?

sqrt ( (-2).abs )
This clearly needs the outer parens.

method_take_two_args arg1, (arg2+arg3)
While this may be valid.

method_take_two_args (arg1+arg2), arg3
But, this would not work and would need to be written as:

method_take_two_args ((arg1+arg2), arg3)
or
method_take_two_args (arg1+arg2, arg3)

Ugh. The more I look into this, the more I like the elegance
of Ruby.
 
J

James Edward Gray II

To be honest, that the following two lines
puts (3+4).abs
puts(3+4).abs
are semantically different *feels* very broken to me. My gut says that
this is a vector for confusion and the introduction of bugs.

That being said, I'm not ready to defend the statement that it *is*
broken. I'll try to live with it for a while and see if I come around.
:)

In Ruby, parenthesis are sometimes optional, just as a convenience to
you the coder. In any midly complex case, just go ahead and include
them and you never need to worry about this again. I leave
parenthesis off:

1. No parameter attributes: object.attr
2. Boolean method tests: if object.is_a? Whatever
3. Simple IO: puts "Printing this out #{(3 + 4).abs}..."

The rest of the time, just add them. If you have to stop and think
for even a second, it's time to add some parenthesis. Then you never
need worry again.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,999
Messages
2,570,246
Members
46,843
Latest member
WizcraftEntertainmentAgen

Latest Threads

Top