有理数-红宝石中的原始数字 [英] rational - original numbers in ruby

查看:145
本文介绍了有理数-红宝石中的原始数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取原始号码? 例如,当我输入:

How do I get the original numbers? For example when I type:

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

2和10将更改为1和5:

2 and 10 will be changed to 1 and 5:

r.numerator   # 1
r.denominator # 5

我如何获得2&是来自Rational类的实例(r)10?

How do I get 2 & 10 from instance of Rational class(r)?

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

I monkey-patched Rational class and created new method(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被存储了吗?

It works, but is there build-in method or variable(s) where original x & y are stored?

推荐答案

不,没有.归约是规范有理数的一种基本且通用的方法.为什么有理数会保留原始的分子和分母?这没有道理.

No, there isn't. Reduction is a basic and common way to normalize rational numbers. Why would a rational number keep the original numerator and denominator? It does not make sense.

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

Your question is like asking "Does a string created by "foo" + "bar" (which becomes "foobar") keep the original substrings "foo" and "bar"? Where are they stored?"

如果您真的想保留原始数字,那么有理数不是您想要的,而Rational的子类化不是正确的方法.您应该使用包含一对数字的数组.

If you really want to keep the original numbers, then a rational number is not what you want, and subclassing Rational is not the right way to go. You should use an array holding a pair of numbers.

这篇关于有理数-红宝石中的原始数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆