ruby中的alias和alias_method

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

 

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

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

 

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

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

如下代码:

 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].f3
10 p [1,2,3].f4

输出:

1
1
1
1

 

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

 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   end
10 end
11 
12 class B < A
13   def method_1
14     p "This is method 1 in B"
15   end
16   
17   rename
18 end
19 
20 B.new.method_2
21 
22


23 class A
24   
25   def method_1
26     p "This is method 1 in A"
27   end
28   
29   def A.rename
30     alias_method :method_2,:method_1
31   end
32 end
33 
34 class B < A
35 
36   def method_1
37     p "This is method 1 in B"
38   end
39   
40   rename
41 end
42 B.new.method_2

输出是

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

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

posted @ 2014-09-12 16:55  smallbottle  阅读(3133)  评论(0编辑  收藏  举报