Reputation: 4941
1 parenthesis:
print ( (1..10).collect do |x| x**2 end )
SyntaxError: compile error
More details:
(irb):1: syntax error, unexpected kDO_BLOCK, expecting ')'
print ( (1..10).collect do |x| x**2 end )
^
(irb):1: syntax error, unexpected kEND, expecting $end
print ( (1..10).collect do |x| x**2 end )
^
2 parentheses:
print (( (1..10).collect do |x| x**2 end ))
149162536496481100=> nil
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
Reputation: 84353
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.
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
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