ruby中的alias和alias_method

寻技术 Ruby编程 2023年07月11日 70

  ruby中的alias和alias_method都可以重命名一个方法,它们的区别如下:

 

1.alias是ruby的一个关键字,因此使用的时候是alias :newname :oldname

   alias_method是Module类的一个方法,因此使用的时候是alias_method :newname,:oldname,有一个逗号。

 

2.alias的参数可以使用函数名或者符号,不能是字符串。

   alias_method的参数可以是字符串,或者符号。

如下代码:

 class Array
   alias :f1 :first
   alias f2 first
   alias_method :f3,:first
   alias_method "f4","first"
 end
 p [1,2,3].f1
 p [1,2,3].f2
 p [1,2,3].f3
 p [1,2,3].f4

输出:




 

3.它们在下面一种情况下有区别。

 class A
   
   def method_1
     p "this is method 1 in A"
   end
   
   def A.rename
     alias :method_2 :method_1
   end
 end
 
 class B < A
   def method_1
     p "This is method 1 in B"
   end
   
   rename
 end
 
 B.new.method_2
 

 class A
   
   def method_1
     p "This is method 1 in A"
   end
   
   def A.rename
     alias_method :method_2,:method_1
   end
 end
 
 class B < A
 
   def method_1
     p "This is method 1 in B"
   end
   
   rename
 end
 B.new.method_2

输出是

"This is method 1 in A"
"This is method 1 in B"

   从结果可以看到,如果是alias_method,调用的是子类的方法,如果用的是alias,调用的是父类的方法。

关闭

用微信“扫一扫”