Ruby Eigenclass详解

经过三个多月的RUBYP实战,重新细读了电子书<Ruby编程语言_涵盖Ruby 1.8和1.9>,终于理解了Eigenclass,也就是我们常说的元类(Metaclass)

目标:[b]证明Kitty类是其Eigenclass的实例[/b]

为了文字好解説,先上代码

class Kitty
def hi
puts 'hi kitty'
end

class << self
Object::A = self #获取Kitty的eigenclass类
def foo
end
end
end

class Object::A #打开Kitty的eigenclass类
def hello
puts 'hello kitty'
end
end

k = Kitty.new
k.hi
Kitty.hello #调用实例方法
puts Object::A.instance_methods.include? 'hello'

# Object::A.new #报can't create instance of virtual class (TypeError) 错误


说明一下关系
[i]k 是Kitty的实例,Kitty是其元类(Eigenclass)的实例[/i]

步骤:
[list=1]
[*]获取Kitty的Eigenclass
[*]打开Kitty的Eigenclass类,定义一个实例方法
[*]Kitty调用实例方法,如果成功,表示,Kitty是其Eigenclass的实例
[/list]

[color=red]事实上,说Kitty类是其Eigenclass的实例我想是不正确的[/color].
看代码

message = "hello"
class << message
def world
puts 'hello world'
end
end
message.world


那么字符串"hello"是谁的实例,是String,还是"hello"的eigenclass的实例?

在书的258页提到方法的查找顺序,首先在对象的eigenclass查找单键方法.
也就是说,对象的单键方法都定义在对象的其eigenclass里
这也就解释了Kitty.singleton_methods为什么会输出["hello","foo"].因为这两个方法都定义在Kitty的eigenclass里

最终结论,[b][color=red]所有的对象都有一个eigenclass,包括类对象Kitty[/color][/b]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值