有理数在初始化时被规范化,因此您无法知道哪些数字作为原始参数给出。您也不能子类Rational
化来安装自己的初始化程序,并且像您一样进行猴子补丁并不是实现您想要实现的目标的最佳方式(我想您知道)。
您可以做的是创建一个代理,Rational
使用BasicObject
它保留原始参数并且不会干扰原始Rational
类的正常操作
class RationalWithArgumentStore < BasicObject
attr_accessor :original_arguments, :rational
def initialize *args
@original_arguments = args
@rational = Rational *args
end
# Basic Object is a basic object, but defines ==
# so let's overwrite it to route to rational
def == other
@rational == other
end
# Route all unknown method calls to rational
def method_missing meth, *args, &block
@rational.send meth, *args, &block
end
end
def RationalWithArgumentStore(*args)
RationalWithArgumentStore.new(*args)
end
所以现在你可以做
my_rational = RationalWithArgumentStore(2,10)
my_rational.original_arguments #=> [2, 10]
#use it like a normal rational
my_rational * 3
my_rational.truncate