【问题标题】:list of ruby operators that can be overridden/implemented可以覆盖/实现的 ruby​​ 运算符列表
【发布时间】:2011-03-20 21:43:34
【问题描述】:

是否有可以覆盖的所有 ruby​​ 运算符的列表? (不是那些不能的!)

【问题讨论】:

  • 重载是对不同的动作使用相同的方法名称,其中方法仅通过其签名来区分。实际上,这在 Ruby 中是不可能的。覆盖或重新定义是这里的恰当术语。
  • 感谢您提供详细信息,@platzhirsch。我已经编辑了这个问题。奇怪的是它通常如何被称为运算符重载,不是吗?
  • 好吧,像我一样,对于术语的使用及其含义总是很挑剔:-) 毕竟它是从像 C++ 这样的语言派生而来的,它可能做同样的事情,但基于不同的语义。

标签: ruby operators operator-overloading


【解决方案1】:

这里是a table of the Ruby operators

方法和可重载的有:

[ ] [ ]=    Element reference, element set
**  Exponentiation
! ~ + -     Not, complement, unary plus and minus (method names for the last two are +@ and -@)
* / %   Multiply, divide, and modulo
+ -     Plus and minus
>> <<   Right and left shift
&   Bitwise `and'
^ |     Bitwise exclusive `or' and regular `or'
<= < > >=   Comparison operators
<=> == === != =~ !~     Equality and pattern match operators (!= and !~ may not be defined as methods)

该表来自 2001 Pickaxe 书中,但与 Ruby 1.9 Pickaxe 书中的表相同——没有理由相信这组中缀运算符会永远改变。

【讨论】:

  • 通过“方法和可重载的”,我假设您的意思是只能重载作为方法的运算符,不是吗?此外,虽然不能重载“纯”运算符,但可以滥用更多类似单词的关键字(例如 defined?notorbegin)作为新方法的名称,而没有任何中缀优点。跨度>
  • 实际上,!= 和 !~ 可以重载/定义,即使旧镐说你不能。早在 2008 年,邮件列表上就有关于它的投诉,Matz 评论说 Ruby 很灵活。
猜你喜欢
  • 2014-04-20
  • 2018-01-19
  • 2010-12-11
  • 2011-03-04
  • 1970-01-01
  • 2017-03-15
  • 2022-11-17
  • 2011-06-01
  • 1970-01-01
相关资源
最近更新 更多