开发者

Do I need to call the Math class directly?

If I'm using a function from the Math module, such as log10, do I need to call Math.log10(number) or ca开发者_开发百科n I do number.log10?


Numbers have no log10 method available by default, but you can extend the Numeric class to add that functionality:

class Numeric

  def log10
    Math.log10 self
  end
end

10.log10
=> 1.0

If you just want to use the methods without having to write Math all the time, you could include Math, then you can call log10 directly:

class YourClass
  include Math

  def method n
    log10 n
  end
end

YourClass.new.method 10
=> 1.0


Why don't you just try, using irb for instance? or just this command line:

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

1.0

ruby -e 'log10(10)'

-e:1:in <main>': undefined methodlog10' for main:Object (NoMethodError)

I guess you have your answer :)

By the way you can include the Math module:

include Math

to be able to use your log10 method without writing it explicitly everytime:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜