O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required