How to use define_method inside initialize()

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

    You were almost there. Just point to the class with self.class, don't even need to use :send:

    class C
      def initialize(n)    
        self.class.define_method ("#{n}") { puts "some method #{n}" }    
      end
    end
    ob = C.new('new_method')
    ob2 = C.new('new_method2')
    # Here ob and ob2 will have access to new_method and new_method2 methods
    

    You can also use it with :method_missing to teach your class new methods like this:

    class Apprentice
      def method_missing(new_method)
        puts "I don't know this method... let me learn it :)"
        self.class.define_method(new_method) do
          return "This is a method I already learned from you: #{new_method}"
        end
      end
    end
    ap = Apprentice.new
    ap.read
    => "I don't know this method... let me learn it :)"
    ap.read
    => "This is a method I already learned from you: read"
    

提交回复
热议问题