看了下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")
执行结果:
i am eating
i am pecking. color is :
im speaking
plume color is:black,i have 2 legs.
Crow's color black
i am come from north,i have 2 legs.
i am come from north,i have 2 legs.
代码说明:
基于以上代码说明,画下以上代码的底层对象模型:
ruby object model
说明:
C代表所属类的意思,左边是对象右边是类。
S代表父子类的意思,下面是子类上边是父类。
从对象模型图可以看出:
类本身也是一个对象,该对象所属的类是一个EigenClass。
类的集成结构,又体现了EigenClass的集成结构。
EigenClass继承自Class
ruby对象的方法查找路径是先向右一步,再往上查,随类实例的方法和实例的方法是隔离的。如crow2的方法一定在#crow2、Crow、Bird、Object、BaseObject里依次查找。而对象Crow的方法一定在#Crow、#Bird、#Object、#BaseObject、Class里依次查找。