解释一下ruby中的特殊方法与特殊类
特殊方法是指某实例所特有的方法。一个对象有哪些行为由对向所属的类决定,但是有时候,一些特殊的对象有何其他对象不一样的行为,在多数程序设计语言中,例如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
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
【解释一下ruby中的特殊方法与特殊类】相关文章
2. Ruby中的保护方法和私有方法与一般面向对象程序设计语言的一样吗
3. 既然说Ruby中一切都是对象,那么Ruby中类也是对象吗
5. 介绍一下Ruby的特点
8. 解释一下抽象方法和抽象类
10. 解释一下ArrayList Vector和LinkedList的实现和区别
本文来源:https://www.mianshiwenti.com/a13479.html
进入下载页面
﹝解释一下ruby中的特殊方法与特殊类﹞相关内容
- 解释一下钝化(Swap out)
- 请解释一下webService? 如何用.net实现webService
- 解释一下Windows的消息机制
- Ruby如何实现动态方法调用
- 女职工在哺乳期享有的特殊劳动保护
- 妇女处于“三期”时的特殊保护
- 代码中finally中的代码会不会执行
- 介绍一下RMI的基本概念
- 介绍一下.NET构架下remoting和webservice
- 介绍一下Python下range()函数的用法