如何获取原始数字?例如,当我输入:
r = Rational(2, 10)
# (1/5)
2 和 10 将更改为 1 和 5:
r.numerator # 1
r.denominator # 5
如何从 Rational 类( r
)的实例中获取 2 和 10
我修补了 Rational 类并创建了新方法(Rational_o
):
def Rational_o *args
x, y = args
r = Rational *args
r.x = x
r.y = y
r
end
class Rational
attr_accessor :x, :y
end
它可以工作,但是是否有存储原始x&y的内置方法或变量?
不,没有。归约是规范有理数的基本和常用方法。为什么有理数会保留原来的分子和分母?这没有意义。
您的问题就像问"由"foo" + "bar"
创建的字符串(变得"foobar"
)是否保持原始子字符串"foo"
和"bar"
?它们存放在哪里?
如果你真的想保留原始数字,那么有理数不是你想要的,子类化Rational
也不是正确的方法。您应该使用包含一对数字的数组。
理数在初始化时被规范化,因此您无法知道哪些数字作为原始参数给出。您也不能Rational
子类来安装自己的初始值设定项,并且像您一样进行猴子修补并不是实现您想要实现的目标的最佳方法(我想您知道)。
您可以做的是围绕BasicObject
Rational
创建一个代理,该代理保留原始参数并且不会干扰原始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
不,没有这样的内置私有或公共方法可以执行您想要的操作。
如果你真的想在实例方法中存储原始数字,你的猴子补丁绝对是这样做的方法之一。
实际上,方法Rational(a,b)
是在类Rational
之外定义的实例方法,有点像Array()
和String()
方法。