alias vs alias_method

Neeraj Singh

By Neeraj Singh

on January 8, 2012

It comes up very often. Should I use alias or alias_method . Let's take a look at them in a bit detail.

Usage of alias

1class User
2
3  def full_name
4    puts "Johnnie Walker"
5  end
6
7  alias name full_name
8end
9
10User.new.name #=>Johnnie Walker

Usage of alias_method

1class User
2
3  def full_name
4    puts "Johnnie Walker"
5  end
6
7  alias_method :name, :full_name
8end
9
10User.new.name #=>Johnnie Walker

First difference you will notice is that in case of alias_method we need to use a comma between the "new method name" and "old method name".

alias_method takes both symbols and strings as input. Following code would also work.

1alias_method 'name', 'full_name'

That was easy. Now let's take a look at how scoping impacts usage of alias and alias_method .

Scoping with alias

1class User
2
3  def full_name
4    puts "Johnnie Walker"
5  end
6
7  def self.add_rename
8    alias_method :name, :full_name
9  end
10end
11
12class Developer < User
13  def full_name
14    puts "Geeky geek"
15  end
16  add_rename
17end
18
19Developer.new.name #=> 'Gekky geek'

In the above case method "name" picks the method "full_name" defined in "Developer" class. Now let's try with alias.

1class User
2
3  def full_name
4    puts "Johnnie Walker"
5  end
6
7  def self.add_rename
8    alias :name :full_name
9  end
10end
11
12class Developer < User
13  def full_name
14    puts "Geeky geek"
15  end
16  add_rename
17end
18
19Developer.new.name #=> 'Johnnie Walker'

With the usage of alias the method "name" is not able to pick the method "full_name" defined in Developer.

This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.

Overall my recommendation would be to use alias_method. Since alias_method is a method defined in class Module it can be overridden later and it offers more flexibility.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.