Extending Ruby Classes

In a few places within my program I want to truncate floating numbers instead of rounding them. So for instance I want to turn 4.56677 into 4.56. Suprisingly Ruby does not provide this function so in the spirit of DRY (don’t repeat yourself) I want to create this function once and be able to use it throughout my application.

All files in the “/config/initializers” directory are loaded with your app so this is the right place to put these kind of things. I can’t think of a good reason not to apply this function to all number types so I am extending the Numeric class and adding a trim_to_digits(digits) method that looks like this:

Now I open a console to ensure that it is working correctly and get the following output:

Hopefully this little tip will help you become more DRY!