【问题标题】:Monkey Patching Float Infix Operator's Produces Unexpected ResultsMonkey Patching Float Infix Operator's 产生意外结果
【发布时间】: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


【解决方案1】:

这似乎是 Ruby 实现中的一个错误。已提交错误报告here

与此同时,您可以切换实现或切换版本。 1.8.7 似乎没有错误。

编辑

This bug 已修复为 revision 44127

【讨论】:

  • 您声称 2.1 没有错误的依据是什么?
  • @sawa IRB 在 2.1 中对我来说没有错误,但是当我将它作为脚本运行时,错误就出现了。
  • 是的 :-) 可爱的虫子! (并固定...)
猜你喜欢
  • 1970-01-01
  • 2017-07-13
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多