面试题答案
一键面试- 为已有实例方法创建别名:
在Ruby中,可以使用
alias_method
方法来为一个已有的实例方法创建别名。例如:class MyClass def original_method puts "This is the original method." end alias_method :new_alias, :original_method end obj = MyClass.new obj.original_method # 输出: This is the original method. obj.new_alias # 输出: This is the original method.
- 重定义方法对原方法调用的影响:
当在Ruby中重定义一个方法时,原方法将被覆盖,不能直接通过原方法名调用。例如:
原方法class MyClass def my_method puts "This is the first definition of my_method." end end obj = MyClass.new obj.my_method # 输出: This is the first definition of my_method. class MyClass def my_method puts "This is the re - defined my_method." end end obj.my_method # 输出: This is the re - defined my_method.
my_method
的第一个定义被覆盖,无法再直接调用。如果想在新定义的方法中调用原方法,可以使用super
关键字,但这通常用于继承场景,这里单纯重定义无法直接调用原方法。