[英]How to open class with alias_method
我最近一直在閱讀Metaprogrammin Ruby 2nd Edition,在第5章末尾,他們提供了一些小測驗,
您的任務是更改
Fixnum
類,以使對1+1
的答案變為3
而不是2
。
我理解課本中的解決方案沒有太多麻煩(他們直接重新打開Fixnum
類)。 但是我想嘗試將方法盡可能地隔離到一個獨立的Module
中。 像下面這樣。
但是在下面運行會導致新定義的+
內部無限翻轉。 您能否指出這段代碼有什么問題? 先感謝您。
module PlusOneMore
def self.prepended(base)
base.class_eval{
alias_method :original_plus, :+
}
end
def +(n)
original_plus(n).original_plus(1)
end
end
Fixnum.class_eval do
prepend PlusOneMore
end
puts 1.+(1)
問題是執行prepended
鈎子時,您的覆蓋已經發生 。 即,當您運行alias_method :original_plus, :+
, +
已經指向您的替代項。
您需要確保在alias_method
調用之后定義了新方法,或者使用其他方法。
module Foo
def self.included(klass)
klass.class_eval do
alias_method :original_plus, :+
define_method(:+) do |n|
original_plus(n).original_plus(1)
end
end
end
end
Fixnum.include(Foo)
puts 1.+(1)
# => 3
您還可以將prepend
與super
和succ
:
module Foo
def +(n)
super(n.succ)
end
end
Fixnum.prepend(Foo)
puts 1.+(1)
# => 3
您還可以使用Ruby改進來達到類似的效果。
module Foo
refine Fixnum do
alias_method :original_plus, :+
def +(n)
(self.original_plus(n)).next
end
end
end
using Foo
puts 1 + 1
#=> 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.