How to use define_method inside initialize()

后端 未结 3 909
名媛妹妹
名媛妹妹 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:23

    I suspect that you're looking for define_singleton_method:

    define_singleton_method(symbol, method) → new_method
    define_singleton_method(symbol) { block } → proc

    Defines a singleton method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod object. If a block is specified, it is used as the method body.

    If you use define_method on self.class, you'll create the new method as an instance method on the whole class so it will be available as a method on all instances of the class.

    You'd use define_singleton_method like this:

    class C
      def initialize(s)    
        define_singleton_method(s) { puts "some method #{s}" }    
      end
    end
    

    And then:

    a = C.new('a')
    b = C.new('b')
    a.a # puts 'some method a'
    a.b # NoMethodError
    b.a # NoMethodError
    b.b # puts 'some method b'
    

    If your initialize did:

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

    then you'd get:

    a.a # puts 'some method a'
    a.b # puts 'some method b'
    b.a # puts 'some method a'
    b.b # puts 'some method b'
    

    and that's probably not what you're looking for. Creating a new instance and having the entire class change as a result is rather odd.

提交回复
热议问题