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?
            Asked
            
        
        
            Active
            
        
            Viewed 4,548 times
        
    1
            
            
         
    
    
        Justin Meltzer
        
- 13,318
- 32
- 117
- 182
2 Answers
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
        
- 17,106
- 3
- 68
- 107
- 
                    You don't need to require Math to use it. – Michelle Tilley Mar 19 '11 at 19:26
- 
                    1@Justin: please take a look at the difference between include and require here: http://stackoverflow.com/questions/318144/what-is-the-difference-between-include-and-require-in-ruby :) – Amokrane Chentir Mar 19 '11 at 19:28
- 
                    @Justin, I think I misunderstood your question. Please take a look at my updated answer. – Matheus Moreira Mar 19 '11 at 19:32
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,907
- 37
- 114
- 158