Ruby 如何在运行时动态创建实例方法?
[ruby 1.8] 假设我有:Ruby 如何在运行时动态创建实例方法?,ruby,metaprogramming,ruby-1.8,Ruby,Metaprogramming,Ruby 1.8,[ruby 1.8] 假设我有: dummy "string" do puts "thing" end 现在,这是对一个方法的调用,该方法有一个字符串和一个块作为输入参数。很好 现在假设我可以有很多类似的调用(不同的方法名,相同的参数)。例如: otherdummy "string" do puts "thing" end 现在因为它们做同样的事情,而且它们可能有数百个,所以我不想为想要的类中的每个对象创建一个实例方法。我更希望找到一种智能的方法,根据一般规则在运行时动态定
dummy "string" do
puts "thing"
end
现在,这是对一个方法的调用,该方法有一个字符串和一个块作为输入参数。很好
现在假设我可以有很多类似的调用(不同的方法名,相同的参数)。例如:
otherdummy "string" do
puts "thing"
end
现在因为它们做同样的事情,而且它们可能有数百个,所以我不想为想要的类中的每个对象创建一个实例方法。我更希望找到一种智能的方法,根据一般规则在运行时动态定义该方法
可能吗?哪些技术是常用的
谢谢我特别喜欢使用
method\u missing
,尤其是当您想要在各种方法调用中使用的代码非常相似时。这里有一个这样的例子-每当有人调用x.boo
并且boo
不存在时,就会使用boo
调用method_missing,boo
的参数和(可选)块:
define\u method
看起来也适合您,但我在这方面的经验不如method\u missing
。以下是来自同一链接的示例:
%w(user email food).each do |meth|
define_method(meth) { @data[meth.to_sym] }
end
是的,有几个选择 第一个是
方法\u缺失
。它的第一个参数是一个符号,它是调用的方法,其余的参数是使用的参数
class MyClass
def method_missing(meth, *args, &block)
# handle the method dispatch as you want;
# call super if you cannot resolve it
end
end
另一个选项是在运行时动态创建实例方法,前提是您事先知道需要哪些方法。这应该在课堂上完成,一个例子如下:
class MyClass
1.upto(1000) do |n|
define_method :"method_#{n}" do
puts "I am method #{n}!"
end
end
end
在需要在运行时创建新实例方法的类方法中调用define\u方法是一种常见模式。使用define\u方法:
class Bar
end
bar_obj = Bar.new
class << bar_obj
define_method :new_dynamic_method do
puts "content goes here"
end
end
bar_obj.new_dynamic_method
我想应该是放上“我是方法”{n}!
。无论如何,回答得好!感谢提供有用的示例(我还需要以这种方式管理方法名)。我肯定会选择method\u missing
作为不知道先验的方法。
class Bar
end
bar_obj = Bar.new
class << bar_obj
define_method :new_dynamic_method do
puts "content goes here"
end
end
bar_obj.new_dynamic_method
content goes here