Milinda Pathirage’s Blog

Computers are fascinating machines, but they’re mostly a reflection of the people using them

Ruby Aliasing

August 13th, 2008 · No Comments · ruby

Aliasing is a powerful Ruby feature that allows more than one method to be referred to by multiple names. This can be used to give a programmer more expressive options or to create copies of a method, allowing you to change the behavior of a class. For an example if you wanted to override to_s to always place quotes around the value (nopt very useful but it will suffice for now) we could write a module like this:
1
2
3
4
5
6
7
8
9
10
11
12
module QuoteToS
  def self.included(base)
    base.class_eval do
      alias_method :to_s_without_quotes, :to_s unless method_defined?(:to_s_without_quotes)
      alias_method :to_s, :to_s_with_quotes
    end
  end
 
  def to_s_with_quotes
    "'#{to_s_without_quotes}'"
  end
end
The above example was taken from this blog post. It describes how to alias a static method in ruby. Also there are some valuable comments in that post and they are worth looking at. With the help of aliasing capability in ruby we can modify ruby methods dynamically. Method modification using aliasing called alias chaninig in ruby and it works like following:
  1. Create an alias for the method to be modified. This alias provides a name for the unmodified version of the method.
  2. Define a new version of the method. This new version should call the unmodified version through the alias, but it can add whatever functionality is needed before and after it does that.
Above steps can be applied repeatedly (as long as a different alias is used each time), creating a chain of methods and aliases. Aliasing can be used in Ruby programming to provide more expressive options to the programmer using the class or to help override methods and change the way that method behave. Aliasing functionality is provide by alias and alias_method keywords. Sphere: Related Content

Related posts brought to you by Yet Another Related Posts Plugin.

Tags:

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment