ruby中的有理原数
如何获得原始数字? 例如,当我键入:ruby中的有理原数,ruby,rational-numbers,Ruby,Rational Numbers,如何获得原始数字? 例如,当我键入: r = Rational(2, 10) # (1/5) 2和10将更改为1和5: r.numerator # 1 r.denominator # 5 如何从Rational类(r)的实例中获得2和10 我修补了Rational类并创建了新方法(Rational\u o): 它可以工作,但是否存在存储原始x&y的内置方法或变量?不,没有。归约是规范化有理数的一种基本且常用的方法。为什么一个有理数会保留原来的分子和分母?这没有道理 您的问题就像问“由“f
r = Rational(2, 10)
# (1/5)
2和10将更改为1和5:
r.numerator # 1
r.denominator # 5
如何从Rational类(r
)的实例中获得2和10
我修补了Rational类并创建了新方法(Rational\u o
):
它可以工作,但是否存在存储原始x&y的内置方法或变量?不,没有。归约是规范化有理数的一种基本且常用的方法。为什么一个有理数会保留原来的分子和分母?这没有道理 您的问题就像问“由
“foo”+“bar”
(成为“foobar”
)创建的字符串是否保留原始子字符串“foo”
和“bar”
?它们存储在哪里?”
如果你真的想保留原始的数字,那么一个有理数就不是你想要的,子类化
rational
不是正确的方法。您应该使用包含一对数字的数组。不,没有这样的内置私有或公共方法可以完成您想要做的事情
如果您真的想在实例方法中存储原始数字,那么monkey补丁肯定是实现这一点的方法之一
事实上,方法
Rational(a,b)
是在类Rational
之外定义的一个实例方法,类似于Array()
和String()
方法。Rational数字在初始化时被规范化,因此您无法知道哪些数字作为原始参数给出。您也不能将Rational
子类化以安装您自己的初始值设定项,而您所做的monkeypatching并不是实现您想要实现的目标的最佳方式(我想您知道)
您可以使用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
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