egor7
egor7

Reputation: 4941

Why do extra parentheses make a difference in this code?

I understand the difference between print (a) do <...> and print(a) do <...>. But what is the difference in my case? Why are two parentheses not the same as one?

Upvotes: 1

Views: 179

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84353

TL;DR

The reason adding extra parentheses "works" is because nested parentheses provide higher precedence to the innermost expression. This disambiguates the tokens for the parser, and allows the statement to be properly evaluated as an expression rather than a method argument.

Analysis

It has to do with the binding precedence of the keywords. Braces have higher precedence than the do/end keywords, so this will work:

print ( (1..10).collect { |x| x**2 } )

because it's interpreting the parenthesized expression as an expression boundary, rather than as bounding a method argument.

You could also do:

print( (1..10).collect do |x| x**2 end )

because here the parentheses bound an argument, rather than separate an expression.

Upvotes: 1

SwiftMango
SwiftMango

Reputation: 15284

Use this:

print((1..10).collect do |x| x**2 end)

And better this:

print((1..10).collect do |x|; x**2; end)

Always remove the space between a method name and parenthesis. It is one of ruby interpreter's syntax analysis. If you put both space and parenthesis, ruby sometimes is not able to correctly interpret.

When you put separate lines of code in one line, use ; to separate (because do end block is supposed to be placed in separate lines)

Upvotes: 0

Related Questions