fdvwpq
Last Updated: February 25, 2016
·
1.007K
· chriswoodford
A42415bd32406503bb231130aacfd4d4

Trigonometric Extensions for Ruby

Add some useful trigonometric conversions to your Ruby code.

NB: Caveat Monkey Patch

Extend the Math module to have methods for converting degrees to radians and vice-versa

module Math

  def self.to_rad(degrees)
    (degrees * Math::PI) / 180
  end

  def self.to_deg(radians)
    radians * (180 / Math::PI)
  end

end

Now you can write

2.0.0p247 :001 > Math.to_rad(45)
 => 0.7853981633974483 

You can take this one step further and extend the Numeric class to have methods for radians and degrees

class Numeric

  def radians
    Math.to_rad(self)
  end

  def degrees
    Math.to_deg(self)
  end

end

Now you can write

2.0.0p247 :002 > 45.radians
 => 0.7853981633974483 
Say Thanks
Respond