动态定义方法

实现一

class Object
  def def(method_name, &block)
    (class << self; self end).send(:define_method, method_name, block)
  end
end

 

具体示例:

 

    x = Object.new
    string = "This is a test"
    x.def(:testing) {puts string + "!"}
    x.testing
    # => This is a test!

 

实现二

    x = Object.new
    class << x
      def testing
        string = "This is a test"
        puts string + "!"
      end
    end
    x.testing  # => This is a test!

 

你可能感兴趣的:(方法)