Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在运行时动态创建实例方法?_Ruby_Metaprogramming_Ruby 1.8 - Fatal编程技术网

Ruby 如何在运行时动态创建实例方法?

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 现在因为它们做同样的事情,而且它们可能有数百个,所以我不想为想要的类中的每个对象创建一个实例方法。我更希望找到一种智能的方法,根据一般规则在运行时动态定

[ruby 1.8]

假设我有:

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