---
title: "【ruby】ruby对象模型"
author: "singleant"
date: "2012-11-27T10:18:53Z"
tags: []
categories: ["编程语言"]
slug: "ruby-ruby"
draft: false
lastmod: "2012-11-27T10:20:35Z"
id: 1735760
url: "https://singleant.iteye.com/blog/1735760"
---

学习ruby，最基础的是理解ruby的对象模型，经过这几天抽空学习，大致总结了下。

 

先看一下代码示例

 

```
class Bird
	@@legs=2
	
	def eat
	   puts "i am eating"
	end

	def comefrom(location)
	   @birthplace=location
	   puts "i am come from #{@birthplace},i have #{@@legs} legs. "
	end
end

class Crow < Bird
    @plumecolor="black"
	
	def peck
	   puts "i am pecking. color is :#{@plumecolor}"
	end
	
	def self.showcolor
		puts "plume color is:#{@plumecolor},i have #{@@legs} legs."
		@plumecolor
	end
end

bird=Bird.new
crow1=Crow.new
crow2=Crow.new
def crow2.speaking
   @canspeak=true
   puts "im speaking"
end
bird.eat
crow1.peck
crow2.speaking
#crow1.speaking
puts "Crow's color #{Crow.showcolor}"
crow2.comefrom("north")
bird.comefrom("north")
```

 代码说明：

 

1.定义了两个类，Bird和Crow，Crow继承了Bird

2.定义了几个不同的变量，实例变量、类实例变量、类变量。@birthplace属于实例变量。@plumecolor属于类实例变量。@@legs属于类变量。从示例可以看出，实例可以访问实例变量和类变量，访问不了类实例变量，

3.crow2和crow1都属于类Crow的对象实例，但是crow2比crow1多一个方法叫speaking。这个方法属于单件方法，存储在对象的eigenclass中。

 

基于以上代码说明，画下以上代码的底层对象模型:

![](http://dl.iteye.com/upload/attachment/0077/1119/bb0648e7-b910-3def-8c1f-a0286773eae8.jpg)  
 说明：

C代表所属类的意思，左边是对象右边是类。

S代表父子类的意思，下面是子类上边是父类。

从对象模型图可以看出：

1.类本身也是一个对象，该对象所属的类是一个EigenClass。

2.类的集成结构，又体现了EigenClass的集成结构。

3.EigenClass继承自Class

4.ruby对象的方法查找路径是先向右一步，再往上查，随类实例的方法和实例的方法是隔离的。如crow2的方法一定在#crow2、Crow、Bird、Object、BaseObject里依次查找。而对象Crow的方法一定在#Crow、#Bird、#Object、#BaseObject、Class里依次查找。