---
title: "2种使用class_eval动态定义方法的格式"
author: "夜鸣猪"
date: "2012-12-12T08:06:36Z"
tags: []
categories: ["编程语言"]
slug: "2-class-eval"
draft: false
lastmod: "2012-12-12T08:06:36Z"
id: 1746244
url: "https://hlee.iteye.com/blog/1746244"
---

```ruby

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'

```



```ruby


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)

```