ITeye博客

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

夜鸣猪 · 2012-12-12 08:06 · Ruby 1.9 · ruby · 编程语言 · Markdown


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)

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。