为什么X-有效的Ruby语句,但它没有做任何事情?
我知道Ruby不支持整数增量x ++
或降低x -
。但是,当我使用它时,它没有任何操作,也不会丢失错误。为什么?
编辑:
对不起,我实际发现的代码使用-x
,哪个略有不同,但问题仍然存在:为什么?
x = 10
while --x > 0
y = x
end
I know ruby doesn't support integer increment x++
or decrement x--
as C does. But when I use it, it doesn't do anything and doesn't throw an error either. Why?
Edit:
Sorry the code I actually found was using --x
, which is slightly different, but the question remains: Why?
x = 10
while --x > 0
y = x
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Ruby 中,运算符是方法。 --x、x++、x== 等都可以做截然不同的事情。
--
和++
本身不是有效的运算符。它们是运算符的组合。对于您提供的代码,
--x
与-(-x)
相同。如果
x == 5
,则-x == -5
和--x == 5
。---x
将是-(-(-x))
,依此类推。同样,单独一行中的
x--
在技术上是有效的,具体取决于下一行代码包含的内容。例如,以下方法是有效的:
该方法的最后两行被解释为
x - (-y)
,计算结果为1 - (-10)
。结果不会分配给任何值,因此
x--
行似乎不执行任何操作,函数只会返回结果:11。您甚至可以有
nil 在函数的最后一行而不是
y
上,并且您不会收到语法错误,但在调用函数时会收到运行时错误。您从x--nil
收到的错误是:这意味着
-nil
无效,因为NilClass
没有定义方法-@
。@
表示-
作为 一元运算符。通过手动调用一元运算符来表达--x
的另一种方法是[电子邮件受保护]@
x--
单独使用是无效的。它需要一个数字对象跟随它(或任何实现-@
的对象)。该对象可以位于下一行。x==
的工作方式相同。In Ruby, operators are methods. --x, x++, x==, etc all can do wildly different things.
--
and++
are not themselves valid operators. They are combinations of operators.In the case of your provided code,
--x
is the same as-(-x)
.If
x == 5
, then-x == -5
and--x == 5
.---x
would be-(-(-x))
, and so on.Similarly,
x--
alone on a line is technically valid, depending on what the next line of code contains.For example, the following method is valid:
The last two lines of that method get interpreted as
x - (-y)
which calculates to1 - (-10)
.The result doesn't get assigned to any value, so the
x--
line would appear to do nothing and the function would just return the result: 11.You could even have
nil
on the last line of the function instead ofy
, and you wouldn't get a syntax error, but you would get a runtime error when the function is called. The error you would receive fromx--nil
is:That means that
-nil
is invalid sinceNilClass
does not define the method-@
. The@
indicates that-
works as a unary operator. Another way to express--x
by invoking the unary operators manually is[email protected]@
x--
just on its own is not valid. It requires a Numeric object to follow it (or any object which implemented-@
). That object can be on the next line.x==
would work the same way.它确实:
x--
不是有效的 Ruby 语法。It does:
x--
is not valid Ruby syntax.