为什么 Ruby 只允许某些运算符重载
在 Ruby 中,与许多其他 OO 编程语言一样,运算符是可重载的。 但是,只有某些字符运算符可以重载。
此列表可能不完整,但以下是一些不能重载的运算符:
!, not, &&, and, ||, or
In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded.
This list may be incomplete but, here are some of the operators that cannot be overloaded:
!, not, &&, and, ||, or
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
" && 和|| 运算符不可重载,主要是因为它们提供无法通过纯方法调用重现的“短路”计算。”
-- Jim Weirich
"The && and || operators are not overloadable, mainly because they provide "short circuit" evaluation that cannot be reproduced with pure method calls."
-- Jim Weirich
方法是可重载的,它们是语言语法的一部分。
Methods are overloadable, those are part of the language syntax.
是的。 运算符不可重载。 只有方法。
有些运营商实际上并非如此。 它们是方法的糖。 所以
5 + 5
实际上是5.+(5)
,而foo[bar] = baz
实际上是foo.[] =(酒吧,巴兹)
。Yep. Operators are not overloadable. Only methods.
Some operators are not really. They're sugar for methods. So
5 + 5
is really5.+(5)
, andfoo[bar] = baz
is reallyfoo.[]=(bar, baz)
.在 Ruby 1.9 中,
!
运算符实际上也是一个方法并且可以被重写。 这只留下&&
和||
及其低优先级对应项and
和or
。还有一些其他无法覆盖的“组合运算符”,例如
a != b
实际上是!(a == b)
和a += b< /code> 实际上是
a = a+b
。In Ruby 1.9, the
!
operator is actually also a method and can be overriden. This only leaves&&
and||
and their low-precedence counterpartsand
andor
.There's also some other "combined operators" that cannot be overriden, e.g.
a != b
is actually!(a == b)
anda += b
is actuallya = a+b
.我们不要忘记
<<
例如:与调用相同:
And let's not forget about
<<
for example:is the same as calling: