使用 << 时出现语法错误,而使用 += 时则不会

Syntax error when using << but not when using +=

ruby 1.8.7

为什么这样可以:

string += method "value"

但这会引发语法错误:

string << method "remove reviewer"

ruby 的新版本是否有相同的行为?

是的,在更高版本的 Ruby 中也有同样的行为。 (我在 Ruby 2.2 上测试过)。

因为Ruby的operator precedence

为了解决这个问题,您可以在 <<:

的情况下使用括号
string << method("remove reviewer")

那么,它应该可以工作,不会出现语法错误。

或者,为了保持一致,您可以为它们都使用括号:

string += method("value")
string << method("remove reviewer")

事实上,强烈建议使用括号 () 进行方法调用,以避免出现您所询问的情况。 检查 this post 了解更多信息。

您可以用 <<=+ 的不同 Operator Precedence 和方法调用来解释此行为。

Ruby 将您的第一个示例读取为:

string += (method "value")

但第二个为:

(string << method) "remove reviewer"

在我看来,即使 Ruby 在很多情况下不需要括号,但在方法调用中使用括号也是一个好习惯。这使得代码更易读,更不容易出错:

string += method("value")
string << method("remove reviewer")