Tuesday, October 2, 2007

Extension Methods and IronRuby

You may or may not be excited about C# getting extension methods but this idea is a core part of Ruby. IronRuby carries this spirit into .NET where it's a simple matter to add a method to an existing class--even a BCL class.

As rich as the BCL classes are, there are times where a bit of functionality is just plain missing. In sticking with true object-oriented practices, Ruby makes it easy to add that functionality where it belongs.

Suppose that you are constantly turning your strings into questions. Instead of creating a Questionizer class that takes a string and manipulates it in some way, wouldn't it be nice to just store our questionizing functionality on the strings themselves? Enter the IronRuby prompt and type the following:
>>> class String
... def questionize
... self + ", eh?"
... end
... end
=> nil

You just added a method to all String objects. Now you can use your method anywhere that you have a string object:
>>> "Nice weather".questionize
=> "Nice weather, eh?"

Now go forth and put your functionality where it clearly belongs!


Anonymous said...

thats no speciality of ironruby.

Ray Vernagus said...


Thanks for the comment! It certainly wasn't my intent to claim that IronRuby is unique in this respect. Boo and F# had the same or similar abilities before both IronRuby and C# did. I was merely comparing what was then a new feature of C# 3.0 to something IronRuby was already doing "out-of-the-box."