Both alias and alias_method in Ruby can be renamed. The differences between them are as follows:
1. Alias is a keyword of Ruby, so it is alias: newname: oldname.
Alias_method is a method of the module class. Therefore, alias_method: newname, oldname, and a comma is used.
2. the alias parameter can be a function name or symbol, not a string.
The alias_method parameter can be a string or a symbol.
The following code:
1 class Array 2 alias :f1 :first 3 alias f2 first 4 alias_method :f3,:first 5 alias_method "f4","first" 6 end 7 p [1,2,3].f1 8 p [1,2,3].f2 9 p [1,2,3].f310 p [1,2,3].f4
Output:
1
1
1
1
3. They are different in the following situations.
1 class A 2 3 def method_1 4 p "this is method 1 in A" 5 end 6 7 def A.rename 8 alias :method_2 :method_1 9 end10 end11 12 class B < A13 def method_114 p "This is method 1 in B"15 end16 17 rename18 end19 20 B.new.method_221 22
23 class A24 25 def method_126 p "This is method 1 in A"27 end28 29 def A.rename30 alias_method :method_2,:method_131 end32 end33 34 class B < A35 36 def method_137 p "This is method 1 in B"38 end39 40 rename41 end42 B.new.method_2
The output is
"This is method 1 in"
"This is method 1 in B"
The result shows that for alias_method, The subclass method is called. If alias is used, the parent class method is called.
Alias and alias_method IN RUBY