Alias

Monday, 4th April 2011

One of the wonderful things I love about Ruby is its ability to add methods to existing classes or, better, objects!

I have recently been using Raimonds Simanovskis’ excellent ruby-plsql-spec gem to test some Oracle code, and found myself wanting to add a filtering method to the resulting output (which is an array of hashes.)

So, I added a simple where method to the returned array:

def result.where(conditions_hash = {})
  self.select do |elem|
    Hash[conditions_hash.select {|k,v| elem[k] == v}] == conditions_hash
  end
end

What I appreciate even more, though, is the ability to “override” an existing method without having to subclass it.

For example, I was writing something recently in Ruby 1.8 and missed 1.9’s Float.round([ndigits]), so I “overrode” the 1.8 version (which doesn’t allow the ndigits parameter) and implemented it myself:

class Float
  alias old_round round
  def round(ndigits = 0)
    n = 10 ** ndigits
    (self * n).old_round.to_f / n
  end
end

Of course, using a default parameter value of 0 (another nifty feature) means that it doesn’t break any existing code that expects it to take no arguments.

There are some downsides to method aliasing that have been written about many times in the past, but judicious use, in a small code base or with good naming conventions is usually enough to avoid most of the pitfalls.