加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何使用method_missing动态声明方法?

发布时间:2020-12-16 21:05:56 所属栏目:百科 来源:网络整理
导读:我有一个 ruby程序,我想接受用户的编写方法,并用该名称创建一个新方法.我试过这个: def method_missing(meth,*args,block) name = meth.to_s class self define_method(name) do puts "hello " + name end endend 我收到以下错误: `define_method': intern
我有一个 ruby程序,我想接受用户的编写方法,并用该名称创建一个新方法.我试过这个:
def method_missing(meth,*args,&block)
  name = meth.to_s
  class << self
    define_method(name) do
      puts "hello " + name
    end
  end
end

我收到以下错误:

`define_method': interning empty string (ArgumentError) in 'method_missing'

有任何想法吗?谢谢.

编辑:

我让它以不同的方式工作,但我仍然很好奇如何以这种方式做到这一点.这是我的代码:

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

解决方法

变量名在类定义(类<< self)范围内不可用.它没有抛出NameError,因为你已经覆盖了method_missing. 要执行您要执行的操作,您需要使用名称保留范围.为了做到这一点,你必须只使用基于块的方法(例如class_eval)而不是直接打开类,所以像这样:
def method_missing(meth,&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,&block)
  eigenclass = class << self; self; end
  eigenclass.class_eval do
    define_method(meth) do
      puts "hello #{meth}"
    end
  end
  send(meth,&block)
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读