MST
星途 面试题库

面试题:Ruby 动态编程特性之元编程与模块

使用Ruby的元编程技术,创建一个模块,该模块可以在运行时为其他类动态添加一组相关的类方法。描述实现思路,并编写完整的Ruby代码示例,同时说明如何避免方法名冲突。
42.2万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建一个模块,利用Ruby的元编程技术,可以通过Module#define_method在运行时定义方法。
  2. 提供一个方法,该方法接受一个类作为参数,然后在这个类上动态添加相关的类方法。
  3. 为了避免方法名冲突,可以在方法名前添加特定的前缀,这样可以确保在目标类中不会与已有的方法名冲突。

Ruby代码示例

module DynamicMethodAdder
  def self.add_class_methods(target_class)
    prefix = 'dynamic_'
    %w(method1 method2 method3).each do |method_name|
      full_method_name = "#{prefix}#{method_name}".to_sym
      target_class.define_singleton_method(full_method_name) do
        puts "This is the dynamic method #{full_method_name}"
      end
    end
  end
end

class MyClass
end

DynamicMethodAdder.add_class_methods(MyClass)
MyClass.dynamic_method1

避免方法名冲突说明

通过在动态添加的方法名前加上特定前缀(如上述代码中的dynamic_),这样就可以显著降低与目标类中现有方法名冲突的可能性。如果需要进一步确认是否冲突,可以在定义方法之前,使用respond_to?方法检查目标类是否已经有同名方法。例如:

if!target_class.respond_to?(full_method_name)
  target_class.define_singleton_method(full_method_name) do
    puts "This is the dynamic method #{full_method_name}"
  end
end

这样就可以在添加方法前进行检查,避免覆盖已有的方法。