Now a number object has a method called percent_of which takes itself and another number as an argument to calculate the percentage.

How Does It Work?

There are two tricks going on here.

The self Keyword

On line 4 the first number in the percent of equation is not passed to the method. Instead, the method refers to the value of its own object. In the example above this is a Numeric object with the value 10. So the value 10 is used.

Extending a Class

More interestingly the Numeric class is part of the standard ruby library. So how come it can be extended? Ruby has a great feature – to add to an existing class just create it within your codebase and add to it. In contrast, other languages might need to use this keyword (or similar) on an object passed to the method (see: C# Extension Methods).

Here this is used to create an elegant result. Within the codebase just add a numeric.rb file with a Numeric class in it. Then the percent_of method can be defined. Ruby will treat it as part of the original class. Pretty neat.