2种使用class_eval动态定义方法的格式

class MyClass
  def initialize(dynamic_methods)
    @arr = Array.new(dynamic_methods)
    @arr.each{|m|
      self.class.class_eval do
        define_method(m) do |*value|
          puts value
        end
      end
    }
  end
end

tmp = MyClass.new %w(method1 method2 method3)


tmp.method1 'abc'



class MyClass
  def initialize(dynamic_methods)
    @arr = Array.new(dynamic_methods)
    @arr.each do |method|
      self.class.class_eval <<-EVAL
        def #{method}(*arguments)
          puts arguments
        end
      EVAL
    end
  end
end

tmp = MyClass.new %w(method1 method2 method3)

你可能感兴趣的:(Ruby,class_eval)