面试题答案
一键面试实现思路
- 创建一个模块,利用Ruby的元编程技术,可以通过
Module#define_method
在运行时定义方法。 - 提供一个方法,该方法接受一个类作为参数,然后在这个类上动态添加相关的类方法。
- 为了避免方法名冲突,可以在方法名前添加特定的前缀,这样可以确保在目标类中不会与已有的方法名冲突。
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
这样就可以在添加方法前进行检查,避免覆盖已有的方法。