如何在initialize()中使用define_method [英] How to use define_method inside initialize()

查看:78
本文介绍了如何在initialize()中使用define_method的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在initialize内使用define_method,但获得不确定的方法define_method.我在做什么错了?

Trying to use define_method inside initialize but getting undefined_method define_method. What am I doing wrong?

class C
  def initialize(n)    
    define_method ("#{n}") { puts "some method #{n}" }    
  end
end

C.new("abc") #=> NoMethodError: undefined method `define_method' for #<C:0x2efae80>

推荐答案

执行以下操作:

class C
  def initialize(n)    
    self.class.send(:define_method,n) { puts "some method #{n}" }    
  end
end

ob = C.new("abc")
ob.abc
# >> some method abc

Module#define_method 私有的方法 class 方法.您无法使用,因为您尝试在C实例上调用它.您必须在C上调用它,使用#send您的情况.

Module#define_method is a private method and also a class method.Your one didn't work,as you tried to call it on the instance of C.You have to call it on C,using #send in your case.

这篇关于如何在initialize()中使用define_method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆