MST

星途 面试题库

面试题:Ruby中方法别名与重定义:基础应用

在Ruby中,如何为一个已有的实例方法创建别名?请举例说明。另外,如果重定义一个方法,原方法的调用会受到怎样的影响?
27.2万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
  1. 为已有实例方法创建别名: 在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.
    
  2. 重定义方法对原方法调用的影响: 当在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关键字,但这通常用于继承场景,这里单纯重定义无法直接调用原方法。