【发布时间】:2015-08-14 16:15:27
【问题描述】:
我有这个模块:
module MyMod
def +(other)
puts "hello"
end
end
这成功地将+ 覆盖为Fixnum:
Fixnum.prepend(MyMod)
123 + :test # outputs "hello"
假设我需要为Fixnum 和其他对象覆盖+ 运算符。这成功地覆盖了+ 的Fixnum 和其他对象:
Fixnum.prepend(MyMod)
Object.include(MyMod)
123 + :test # outputs "hello"
但如果我更改prepend 和include 的顺序,我的覆盖无效:
Object.include(MyMod)
Fixnum.prepend(MyMod)
123 + :test # error: -:10:in `+': :test can't be coerced into Fixnum (TypeError)
为什么include和prepend的顺序在这里会有这个效果?
【问题讨论】:
-
哦,顺便说一句,这就是我用它的目的:gist.github.com/henrik/36b991205d6c772b5a1f#file-pipeline1-rb