带有 i++ 的 Ruby 括号语法异常++i
为什么这会引发语法错误?我希望它是相反的...
>> foo = 5
>> foo = foo++ + ++foo
=> 10 // also I would expect 12...
>> foo = (foo++) + (++foo)
SyntaxError: <main>:74: syntax error, unexpected ')'
foo = (foo++) + (++foo)
^
<main>:75: syntax error, unexpected keyword_end, expecting ')'
尝试使用 tryruby.org 它使用 Ruby 1.9.2。
在 C# (.NET 3.5) 中,这工作得很好,并且产生了另一个结果:
var num = 5;
var foo = num;
foo = (foo++) + (++foo);
System.Diagnostics.Debug.WriteLine(foo); // 12
我猜这是一个运算符优先级的问题?有人能解释一下吗?
为了完整性...
C 返回 10
Java 返回 12
Why does this throw a syntax error? I would expect it to be the other way around...
>> foo = 5
>> foo = foo++ + ++foo
=> 10 // also I would expect 12...
>> foo = (foo++) + (++foo)
SyntaxError: <main>:74: syntax error, unexpected ')'
foo = (foo++) + (++foo)
^
<main>:75: syntax error, unexpected keyword_end, expecting ')'
Tried it with tryruby.org which uses Ruby 1.9.2.
In C# (.NET 3.5) this works fine and it yields another result:
var num = 5;
var foo = num;
foo = (foo++) + (++foo);
System.Diagnostics.Debug.WriteLine(foo); // 12
I guess this is a question of operator priority? Can anybody explain?
For completeness...
C returns 10
Java returns 12
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 中没有
++
运算符。 Ruby 将您的foo++ + ++foo
并将这些加号中的第一个作为二元加法运算符,将其余的作为第二个上的一元正运算符foo
.因此,您要求 Ruby 将 5 和 (plus plus plus plus) 5 添加,即 5,因此结果为 10。
当您添加括号时,Ruby 会在第一个结束操作之前查找第二个操作数(用于二进制加法)括号,并因为找不到括号而抱怨。
您从哪里得知 Ruby 支持 C 风格的
++
运算符?把那本书扔掉。There's no
++
operator in Ruby. Ruby is taking yourfoo++ + ++foo
and taking the first of those plus signs as a binary addition operator, and the rest as unary positive operators on the secondfoo
.So you are asking Ruby to add 5 and (plus plus plus plus) 5, which is 5, hence the result of 10.
When you add the parentheses, Ruby is looking for a second operand (for the binary addition) before the first closing parenthesis, and complaining because it doesn't find one.
Where did you get the idea that Ruby supported a C-style
++
operator to begin with? Throw that book away.Ruby 不支持此语法。请改用
i+=1
。正如 @Dylan 提到的,Ruby 将您的代码读取为
foo + (+(+(+(+foo))))
。基本上,它读取所有+
符号(在第一个符号之后)作为标记整数正值。Ruby does not support this syntax. Use
i+=1
instead.As @Dylan mentioned, Ruby is reading your code as
foo + (+(+(+(+foo))))
. Basically it's reading all the+
signs (after the first one) as marking the integer positive.Ruby 没有
++
运算符。在您的示例中,它仅添加第二个 foo,“消耗”一加,并将其他视为一元 + 运算符。Ruby does not have a
++
operator. In your example it just adds the second foo, "consuming" one plus, and treats the other ones as unary + operators.