How to Use alias and alias_method in Ruby

09/20/2021

Contents

In this article, you will learn how to use alias and alias_method in Ruby.

Using alias and alias_method

In Ruby, alias and alias_method are two methods that are used to give an alternative name to an existing method or to create a new method with the same implementation as an existing method.

Here’s how to use them:

alias keyword

The alias keyword is used to create a new name for an existing method. Its syntax is:

alias new_name old_name

For example, if you want to give the method say_hello an alternative name greet, you can use alias as follows:

def say_hello
  puts "Hello!"
end

alias greet say_hello

greet # Output: Hello!

alias_method method

The alias_method method is similar to the alias keyword, but it can be used to alias a method from any class, not just the current one. Its syntax is:

alias_method :new_name, :old_name

For example, if you have a class Person with a method introduce and you want to give it an alternative name greet, you can use alias_method as follows:

class Person
  def introduce
    puts "Hello, my name is #{name}."
  end
  
  alias_method :greet, :introduce
end

person = Person.new
person.greet # Output: Hello, my name is .

Note that alias and alias_method are different in that alias can only be used within the context of the current class or module, whereas alias_method can be used to alias methods from any class. Additionally, alias_method is more flexible in that it can be used to alias private methods, whereas alias cannot.