Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/23.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_Closures_Metaprogramming - Fatal编程技术网

Ruby 我如何动态声明一个方法,而方法_丢失?

Ruby 我如何动态声明一个方法,而方法_丢失?,ruby,closures,metaprogramming,Ruby,Closures,Metaprogramming,我有一个ruby程序,我想接受用户的编造方法,并用这个名称生成一个新方法。我试过这个: def method_missing(meth,*args,&block) name = meth.to_s class << self define_method(name) do puts "hello " + name end end end 有什么想法吗?谢谢 编辑: 我用另一种方式工作,但我仍然好奇如何用这种方式工作。这是我的密码: de

我有一个ruby程序,我想接受用户的编造方法,并用这个名称生成一个新方法。我试过这个:

def method_missing(meth,*args,&block)
  name = meth.to_s
  class << self
    define_method(name) do
      puts "hello " + name
    end
  end
end
有什么想法吗?谢谢

编辑:

我用另一种方式工作,但我仍然好奇如何用这种方式工作。这是我的密码:

def method_missing(meth,*args,&block)
  Adder.class_eval do
    define_method(meth) do
      puts "hello " + meth
    end
  end
  send("#{meth}")
end

变量
name
在类定义中不可用(
class问题在于
class@Aditya Sanghi:谢谢你的更正。但我实际上是想切换到插值,它更全面(更快、更少的垃圾、读取更干净、使用符号!)。而不是
eigenclass=class
def method_missing(meth,*args,&block)
  Adder.class_eval do
    define_method(meth) do
      puts "hello " + meth
    end
  end
  send("#{meth}")
end
def method_missing(meth,*args,&block)
  name = meth.to_s
  eigenclass = class << self; self; end
  eigenclass.class_eval do
    define_method(name) do
      puts "hello " + name
    end
  end
end
def method_missing(meth,*args,&block)
  eigenclass = class << self; self; end
  eigenclass.class_eval do
    define_method(meth) do
      puts "hello #{meth}"
    end
  end
  send(meth, *args, &block)
end