[ruby] How to add new method in a class

原创文章,转载请注明来源并保留原文链接

Look at the below example:

module M
  def a
    p "aaaa"
  end
end

class A
  include M

  def self.create_method(name, &block)
    M.send(:define_method, name, &block)
  end
end

a = A.new

hello = %q{def hello() p "Hello there!"; a end}

M.module_eval(hello)

a.hello # Event i has created `a` already
# "Hello there!"
# "aaaa"

A.create_method :foo do
  puts 'I am fool'
end

a.foo # => I am fool

Leave a Reply

Your email address will not be published. Required fields are marked *