【发布时间】:2013-12-28 08:49:03
【问题描述】:
重新定义Float#/似乎没有效果:
class Float
def /(other)
"magic!"
end
end
puts 10.0/2.0 # => 5.0
但是当另一个中缀运算符Float#*被重新定义时,Float#/突然接受了新的定义:
class Float
def /(other)
"magic!"
end
def *(other)
"spooky"
end
end
puts 10.0/2.0 # => "magic!"
我很想听听是否有人能解释这种行为的根源,以及其他人是否得到相同的结果。
- Ruby:ruby 2.0.0p353 (2013-11-22) [x64-mingw32]
要快速确认错误,请运行this script。
【问题讨论】:
-
已在 Ubuntu 13.04 和 Ruby 2.0.0p247 上确认。也许这被列为错误? Ruby Issue Tracker
-
有趣的是,
10.0/2.0返回一个浮点数,10.0.send(:/,2.0)返回"magic!" -
已报告。 Ruby Issue Tracker
-
我在 Linux 上得到了相同的结果,并且由于所有三个主要平台(Windows、Mac OS、Linux)的行为都相同,因此看起来操作系统无关紧要。我相应地从问题中删除了操作系统描述。
-
@Marc-AndréLafortune 刚刚看了你的演讲。愉快!感谢您(感谢您的工作和演讲)并感谢您的链接。 :-)
标签: ruby monkeypatching arithmetic-expressions