在 Ruby 中,一切皆对象。这就是为什么我不明白为什么我们有 Math 模块。在我看来,Math 模块中的大部分(全部?)函数应该是 Integer、Float 等数字类型的方法。
例如而不是
Math.sqrt(5)
这样会更有意义
5.sqrt
sin
、cos
、tan
、log10
等也是如此。
有谁知道为什么所有这些函数最终都在数学模块中?
最佳答案
我不知道 Ruby 的早期历史,但我感觉 Math 模块是在 C
但是,它是 Ruby!所以你总能摆脱猴子补丁!
class Float
def sqrt; Math.sqrt(self); end
def sin; Math.sin(self); end
def cos; Math.cos(self); end
def tan; Math.tan(self); end
def log10; Math.log10(self); end
end
关于ruby - 为什么 sqrt() 不是 Numeric 上的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2844526/