[转帖]ruby 对象的特殊方法

[size=large][转帖]ruby 对象的特殊方法[/size]
原文:[url]http://fujinbing.iteye.com/blog/1125884[/url]


特殊方法是指某实例所特有的方法。一个对象有哪些行为由对向所属的类决定,但是有时候,一些特殊的对象有何其他对象不一样的行为,在多数程序设计语言中,例如C++和Java,我们必须定义一个新类,但在Ruby中,我们可以定义只从属于某个特定对象的方法,这种方法我们成为特殊方法(Singleton Method)。

class SingletonTest 
def info
puts "This is This is SingletonTest method"
end
end

obj1 = SingletonTest.new
obj2 = SingletonTest.new

def obj2.info
puts "This is obj2"
end

obj1.info
obj2.info


执行结果为:
This is This is SingletonTest method
This is obj2


有时候,我们需要给一个对象定义一系列的特殊方法,如果按照前面的方法,那么只能一个一个定义:

def obj2.singleton_method1 
end

def obj2.singleton_method2
end

def obj2.singleton_method3
end
……
def obj2.singleton_methodn
end


这样做非常繁复麻烦,而且无法给出一个统一的概念模型,因此Ruby提供了另外一种方法,
class << obj
……
end

obj是一个具体的对象实例,class << 代表它的特殊类。

class SingletonTest 
def meth1
puts "This is meth1"
end

def meth2
puts "This is meth2"
end
end

obj1 = SingletonTest.new
obj2 = SingletonTest.new

class << obj2
def meth1
puts "This is obj2's meth1"
end

def meth2
puts "This is obj2's meth2"
end
end

obj1.meth1
obj1.meth2
obj2.meth1
obj2.meth2


执行结果为:
This is meth1
This is meth2
This is obj2's meth1
This is obj2's meth2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值