---
title: "令人迷惑的class_eval和instance_eval"
author: "googya"
date: "2010-05-31T17:27:38Z"
tags: []
categories: ["编程语言"]
slug: "class-eval-instance-eval"
draft: false
lastmod: "2010-08-31T11:03:41Z"
id: 680125
url: "https://googya.iteye.com/blog/680125"
---

按照[**yugui**](http://yugui.jp) 大姐的说法，class\_eval和instance\_eval有如下的区别：

class&amp;instance\_eval              self                            default definee  
class\_eval                          the receiver                   the receiver  
instance\_eval                   the receiver                     eigenclass of the receiver

上面就是class\_eval与instance\_eval的区别了，一般情况下这个没有问题（个人感觉）。但还是会有令迷惑的地方。  
下面的例子说明了，在下面情况下，class\_eval和instance\_eval的作用没有区别。

```
class A
end
class Object
	def eigenclass
		class << self;self;end
	end
end
A.class_eval do
p self
	def hehe
		"hehe"
	end
	define_method(:xixi) do
		"xixi"
	end
end

A.instance_eval do
p self
	def haha;"haha";p self ;end
end

A.instance_eval do
p self
	define_method(:hihi) do
		"hihi"
		p self.to_s
	end
end
 
 A.haha
 A.new.hihi
 p A.instance_methods
 p  "*"*120
 p A.eigenclass.instance_methods
```

    定义的hihi和xixi都是A是实例方法。

 [jayfield](http://blog.jayfields.com/2007/03/ruby-instanceeval-and-classeval-method.html)    
说到：

define\_method always defines an instance method on the target (Foo in our example). This makes sense because define\_method is being call on the implicit self, which evaluates to the receiver (Foo) in our example."[/

 

jayfield的说法应该是有问题的，但不这样理解，上面的例子怎么又说得通呢？

PS:可能是我表述不清还是怎么的，基本上没有人对此关注。实际上我想说的就是：

```
A.instance_eval do 
p self 
def haha;"haha";p self ;end 
end 

A.instance_eval do 
p self 
define_method(:hihi) do 
"hihi" 
p self.to_s 
end 
end 
```

 

   同样是用instance\_eval,为什么有这么大的不同。

```
A.new.hihi 
A.haha 
```

 

事实上，

A.instance\_eval do  
p self  
define\_method(:hihi) do  
"hihi"  
p self.to\_s  
end  
end

 

 

与 class A

 

  define\_method(:hihi) do

     "hihi"

 

end

end

的效果是一样的，define\_method是个私有方法，能调用（隐式）它的只能是类对象而非一般的对象。

 

 

 

 

  在一个[网站](http://vision-media.ca/resources/ruby/understanding-ruby-metaclasses) 上看到了这个：

 

![](http://dl.iteye.com/upload/attachment/300996/983cc161-09fb-3fdf-9c3f-a6756980a5a7.png)

 

现在可以比较直观的理解这二者的不同了