Home »
Ruby programming
alias vs alias_method in Ruby
Ruby alias vs alias_method: Here, we are going to learn about the alias and alias_method in Ruby programming language with its syntaxes and examples.
Submitted by Hrithik Chandra Prasad, on September 12, 2019
alias vs alias_method
Before differentiating alias and alias_method, it is required to understand what an alias method does in any programming language? So, alias identifies a memory location which can be accessed by different symbolic notations or you can say by creating an alias, you provide the same memory to different symbols. The data stored in the variable are accessible to many symbolic names in a program. If the programmer makes any change in the data through a symbol, then the data will be changed for all the aliased symbols. This makes the program complex and difficult to be understood.
Ruby provides you two ways by which you can create an alias. First one is an alias and the second one is alias_method. Now let us see the code for each and will analyze, which one is better later on.
1) 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.
2) 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.