ruby - 猴子修补 float 中缀运算符产生意想不到的结果

标签 ruby monkeypatching arithmetic-expressions

重新定义 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 .

最佳答案

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

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

编辑

This bug已修复 revision 44127

关于ruby - 猴子修补 float 中缀运算符产生意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501203/

相关文章:

ruby-on-rails - Ruby 哈希值遍历和更改值不起作用

ruby - 如何在 Ruby 中关闭 $stdout 和 $stderr

javascript - 将 Google Analytics cookie 转换为本地/ session 存储

c++ - 推导模板参数表达式的类型

ruby-on-rails - 如何从月份编号获取月份名称

mysql - 查询 rails 中的加入关联

ruby - 猴子补丁核心类的替代品

python - 从 ctypes.Union 派生的 Monkey Patching 类不起作用

c - printf() 正在打印错误的值

bash - 如何在 bash 中使用 mod 运算符?