Ruby to Classes: Open up, we’re coming in!

June 12, 2007

Ruby has open classes. “Who cares?” you say. You should. Yes you! Open classes really simplify a lot of programming problems when you can learn to use them correctly. First and foremost, what does it mean to have open classes? Well, this means that you, the programmer, can crack open ANY class and add methods to your heart’s desire! And nothing is off limits. This means I can break into the Integer class, add a helpful method for my program, and sneak out again without anyone being the wiser.

So how would one use the the fiendishly clever practice of open classes in every day coding? Here’s an example of a problem I ran into while working on project euler problems:

I often found that I needed to know the number of digits in an Integer for solving these problems. Let’s say I want to get the sum of the number of digits in all the numbers 1..100. Here’s the old way:

Old Way

Now this is all fine and dandy and the code works great. However, there is a logical conundrum here. Why is num_digits just hanging out there by itself? We know that this method will always be called on Integers and, therefore, it makes much more sense to add a new instance method to the Integer class. Ruby open classes to the rescue!

Super fabulous open classes way!

Ahh, I feel so much better, don’t you? The only subtlety here is that we’re using self inside our num_digits method. This simply references the instance of the integer we are currently dealing with. So remember, next time you find yourself writing a method that would be better suited as an instance method of a class, break on in there! Ruby classes aren’t shy.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: