#16 Adding Commas to Numbers (commify.rb)

A standard way of formatting numbers is to present them with commas (or some other delimiter) separating each group of thousands. Our next script does that by adding a method called commify to all numbers. You might think that we could do this by opening the Integer class and adding a new method to it, as we did in power_of.rb. This is certainly a reasonable approach, except that we may want to use commify on floating-point numbers as well. What’s the solution?

Inheritance

The answer deals with an object-oriented concept called inheritance. We discussed this earlier in Chapter 3 when we added methods to the Object class. Inheritance is what allows all other classes to use methods of the Object class, because ...

Get Ruby by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.