i++ ++i 的 Ruby 括号语法异常 [英] Ruby Parenthesis syntax exception with i++ ++i

查看:55
本文介绍了i++ ++i 的 Ruby 括号语法异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会抛出语法错误?我希望它是相反的...

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 ')'   

使用 Ruby 1.9.2 的 tryruby.org 进行了尝试.

Tried it with tryruby.org which uses Ruby 1.9.2.

在 C# (.NET 3.5) 中,这可以正常工作并产生另一个结果:

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?

为了完整性...
C 返回 10
Java 返回 12

For completeness...
C returns 10
Java returns 12

推荐答案

Ruby 中没有 ++ 运算符.Ruby 将您的 foo++ + ++foo 并将这些加号中的 第一个 作为二元加法运算符,其余作为第二个 上的一元正运算符foo.

There's no ++ operator in Ruby. Ruby is taking your foo++ + ++foo and taking the first of those plus signs as a binary addition operator, and the rest as unary positive operators on the second foo.

所以你要求 Ruby 加 5 和(加加加加)5,即 5,因此结果是 10.

So you are asking Ruby to add 5 and (plus plus plus plus) 5, which is 5, hence the result of 10.

当您添加括号时,Ruby 会在第一个右括号之前寻找第二个操作数(用于二进制加法),并因为找不到而抱怨.

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.

您是从哪里得知 Ruby 支持 C 风格的 ++ 运算符的?把那本书扔掉.

Where did you get the idea that Ruby supported a C-style ++ operator to begin with? Throw that book away.

这篇关于i++ ++i 的 Ruby 括号语法异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆