Why is sqrt() not a method on Numeric? Why is sqrt() not a method on Numeric? ruby ruby

Why is sqrt() not a method on Numeric?


I don't know the early history of Ruby, but I have a feeling the Math module was modelled after the C <math.h> header. It is an odd duck in the Ruby standard library though.

But, it's Ruby! So you can always bust out the monkey patching!

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); endend


To expand on Michael's answer, there's no need to define all those methods by hand. Note that I explicitly skip the two Math methods that take two arguments.

class Numeric  (Math.methods - Module.methods - ["hypot", "ldexp"]).each do |method|    define_method method do      Math.send method, self    end  endendputs 25.sqrtputs 100.log10

Output:

5.02.0 

In regards to exactly why those methods are not included in Numeric already, I'm really not sure of a good reason. I don't think namespace pollution as Andrew mentioned is particularly a risk in the Numeric class; Michael is probably on the right track with historic carryover.


I've rewritten Mark's answer to be more concise, and not require removing hypot and ldexp, since I'm using this approach myself.

class Numeric  Math.methods(false).each do |method|    define_method method do |*args|      Math.send(method, self, *args)    end  endend>> 3.hypot(4)=> 5.0>> Math::PI.sqrt=> 1.7724538509055159>> 10.log10=> 1