理性 – ruby中的原始数字

我如何获得原始数字? 例如,当我键入:

r = Rational(2, 10) # (1/5) 

2和10将更改为1和5:

 r.numerator # 1 r.denominator # 5 

如何从Rational class( r )的实例获得2和10?

我修补了Rational类并创建了新方法( Rational_o ):

 def Rational_o *args x, y = args r = Rational *args rx = x ry = y r end class Rational attr_accessor :x, :y end 

它有效,但有存储原始x和y的内置方法或变量吗?

不,没有。 减少是规范有理数的基本和常用方法。 为什么有理数会保留原始分子和分母? 它没有任何意义。

你的问题就像是问“由"foo" + "bar" (变成"foobar" )创建的字符串是否保留原始子字符串"foo""bar" ?它们存储在哪里?”

如果你真的想保留原始数字,那么理性数字就不是你想要的,而inheritanceRational并不是正确的方法。 你应该使用一个包含一对数字的数组。

有理数在初始化时得到规范化,因此您无法知道哪些数字作为原始参数给出。 您也不能将Rational子类化为安装自己的初始化程序,并且monkeypatching正如您所做的那样,并不是实现您想要实现的目标的最佳方式(我认为您知道)。

您可以做的是在Rational with 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 

不,没有这样的内置私有或公共方法可以做你想做的事情。

如果你真的想将原始数字存储在实例方法中,那么你的猴子补丁肯定是其中一种方法。

实际上,方法Rational(a,b)是在类Rational之外定义的实例方法,类似于Array()String()方法。