How to use define_method inside initialize()

后端 未结 3 916
名媛妹妹
名媛妹妹 2021-02-01 03:56

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

class C
          


        
3条回答
  •  庸人自扰
    2021-02-01 04:10

    Do as below :

    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 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.

提交回复
热议问题