我需要直接调用Math类吗?

时间:2011-03-19 19:16:54

标签: ruby-on-rails ruby ruby-on-rails-3

如果我正在使用Math模块中的函数,例如log10,我是否需要拨打Math.log10(number)或我可以number.log10吗?

2 个答案:

答案 0 :(得分:2)

默认情况下,数字没有log10方法可用,但您可以扩展Numeric类以添加该功能:

class Numeric

  def log10
    Math.log10 self
  end
end

10.log10
=> 1.0

如果您只是想在不必一直写Math的情况下使用这些方法,可以include Math,然后直接拨打log10

class YourClass
  include Math

  def method n
    log10 n
  end
end

YourClass.new.method 10
=> 1.0

答案 1 :(得分:2)

为什么不尝试使用irb?或者只是这个命令行:

ruby -e 'puts Math.log10(10)'
  

1.0

ruby -e 'log10(10)'
  

-e:1:在<main>': undefined method log10'中为main:Object   (NoMethodError)

我猜你有答案:)。

顺便说一句,您可以包含数学模块:

include Math

能够使用你的log10方法,而不是每次都明确地写它:

 ruby -e 'include Math; puts log10(10)'
  => 1.0