Alias and alias_method IN RUBY

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.