Home »
Ruby Tutorial
alias vs alias_method in Ruby
By IncludeHelp Last updated : December 01, 2024
Understanding Alias Methods
Before differentiating alias
and alias_method
, it is important to understand what an alias method does in any programming language.
What is an Alias?
An alias identifies a memory location that can be accessed by different symbolic notations. In other words, by creating an alias, you provide the same memory to different symbols. The data stored in the variable is accessible to many symbolic names in a program. If the programmer makes any change in the data through a symbol, the data will be changed for all the aliased symbols. This can make the program complex and difficult to understand.
Creating an Alias in Ruby
Ruby provides you with two ways to create an alias. The first one is alias
, and the second one is alias_method
. Now, let us see the code for each and analyze which one is better later on.
alias Method Example
class Human
def Human_age
puts "Enter the age"
@ag = gets.chomp
puts "Age is #{@ag}"
end
alias age Human_age
end
Human.new.age
Output
Enter the age
12
Age is 12
In the above code, you can observe that we are creating an alias of method Human_age by the name age. When we are creating its object and calling the age, it is ultimately calling the Human_age method.
It is only creating an alias.
alias_method Example
class Human
def Human_age
puts "Enter the age"
@ag = gets.chomp
puts "Age is #{@ag}"
end
alias_method :age, :Human_age
end
Human.new.age
Output
Enter the age
67
Age is 67
In the above code, instead of creating an alias, we are now creating an alias method by the name age. When we are calling age with the instance of class Human, we are calling the Human_age method.
Now let us figure our differences between them.
Differences between alias and alias_method
- We need to put , between old_method_name and new_method_name in the case of alias_method which directly shows that alias_method requires String as well as a symbol as arguments.
- If we talk about the scope of alias and alias_method, then we can conclude that alias is linguistically scoped which simply means that it considers itself as the value of "self" during the source code is read whereas if we talk about alias_method, it considers value of self as the value determined at the Run time.
- alias is a keyword whereas alias_method is a method defined in the Module. Due to this fact, alias_method can be overridden.
Since alias_method facilitates you with more versatility and flexibility, it is better to use alias_method instead of alias keyword.