1
  • 1个括号:

    print ( (1..10).collect do |x| x**2 end )
    SyntaxError: compile error
    

    更多细节:

    (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个括号:

    print (( (1..10).collect do |x| x**2 end ))
    149162536496481100=> nil
    

print (a) do <...>我理解和之间的区别print(a) do <...>。但我的情况有什么不同?为什么两个括号不一样?

4

2 回答 2

1

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.

于 2012-06-24T17:08:51.463 回答
0

用这个:

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

更好的是:

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

始终删除方法名称和括号之间的空格。它是 ruby​​ 解释器的语法分析之一。如果同时放置空格和括号,ruby 有时无法正确解释。

当您将单独的代码行放在一行中时,使用;to 分隔(因为 do end 块应该放在单独的行中)

于 2012-06-24T17:19:56.687 回答