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!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">