1

If I'm using a function from the Math module, such as log10, do I need to call Math.log10(number) or can I do number.log10?

Justin Meltzer
  • 12,978
  • 32
  • 114
  • 178

2 Answers2

3

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
Matheus Moreira
  • 16,620
  • 3
  • 64
  • 103
1

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
Amokrane Chentir
  • 29,280
  • 37
  • 112
  • 157