新人学ruby---alias,alias_method,alias_method_chain,undef,undef_method的区别

来源:互联网 发布:用友进销存软件 编辑:程序博客网 时间:2024/05/21 15:05

今天在看calabash的wait_helpers.rb类时偶然看到了 “alias_method”。 不解,就顺便查下文档,发现几个相关关键字就索性做下记录,以便以后翻阅。


alias

alias 给已经存在的方法或全局变量设置一个别名,在重新定义已经存在的方法是,还能通过别名来调用原来的方法。alias方法的参数为方法名或者符号名。

语法:
alias 别名 原名 #直接使用方法
alias :别名 :原名 #使用符号名

例子:
a
代码:

    class AliasDemo      $old = "old"      def hello        puts "old_hell0"      end    end    class Demo2 < AliasDemo      # 给hello方法取别名      alias old_hello hello      # 给全局变量$old取别名      alias $new_in_old $old      def hello        puts "new_hello"      end    end    obj = Demo2.new    obj.hello    obj.old_hello    puts $new_in_old

输出结果:
new_hello
old_hell0
old

alias_method

作用和alias差不多,是Module的一个私有实例方法,只能用于给方法起别名,并且参试只能是字符串或者符号(alias 后面跟的是方法名或者全局变量)而且参数间是用“,”隔开(alias是用空格隔开)。

语法:
alias_method :new_name, :old_name

例子:
代码:

    class AliasMethodDemo      def b        puts "b"      end      alias_method :b_new, :b      b = AliasMethodDemo.new      b.b_new      b.b    end

输出结果:
b
b

alias_method_chain

技术文档总是会过时的,百度还能找到这个关键字的说明,然而已经不再使用了。


undef 和 undef_method

这两个方法效果的等效的,都是用于取消方法定义。undef不能出现再方法主体内。undef和rails一样,参数可以指定方法名或者符号名,undef_method后面参试只能是字符串或者符号 。如果一个类继承了某个父类,使用了这两个方法取消方法,会连带父类也会一起取消。

语法:
undef 方法名 #直接使用方法名
undef :方法名 #使用符号名
undef_method :方法名

remove_method

如果你只想移除子类的方法,而不想移除父类的方法,那么remove_method符合你需求。
语法:
remove_method :方法名

例子:
代码:

    class Parent      def hello        puts "In parent"      end    end    class Child < Parent      def hello        puts "In child"      end    end    c = Child.new    c.hello    class Child      remove_method :hello # 移除子类的hello方法,父类还在    end    c.hello    class Child      undef_method :hello # 连父类的hello方法一起删除,不允许任何地方调用 'hello'      # undef hello  # 等效上面的undef_method    end    c.hello

输出结果:
=>:in <top (required)>': undefined methodhello’ for # (NoMethodError)
from -e:1:in load'
from -e:1:in

In child
In parent

0 0