解释一下ruby中的特殊方法与特殊类?
来源:互联网 发布:the stone roses 知乎 编辑:程序博客网 时间:2024/06/06 01:53
解释一下ruby中的特殊方法与特殊类?
Ruby[AD]
特殊方法是指某实例所特有的方法。一个对象有哪些行为由对向所属的类决定,但是有时候,一些特殊的对象有何其他对象不一样的行为,在多数程序设计语言中,例如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
- 解释一下ruby中的特殊方法与特殊类?
- 类中的集中特殊方法
- Python中的特殊方法
- ruby入门_特殊类
- python类中的特殊属性and特殊方法and特殊文件
- Python(私有变量)类中的特殊方法
- Python(私有变量)类中的特殊方法
- Python(私有变量)类中的特殊方法
- Python(私有变量)类中的特殊方法
- Python(私有变量)类中的特殊方法
- Python(私有变量)类中的特殊方法
- Python(私有变量)类中的特殊方法
- 关于python中的特殊方法
- python中的用来定制类的特殊方法的含义
- python中的用来定制类的特殊方法的含义
- str类中的特殊方法和更多字符串
- 类中的一些特殊函数
- PYTHON类的特殊方法
- FreeSwitch B2B 状态转换流程(1)
- 启示录收集
- java,静态与伪静态
- 预处理 #error 的作用
- android 滚动条 相关属性
- 解释一下ruby中的特殊方法与特殊类?
- 007 SG 注意事项 04
- JSpider学习二 —— 应用示例
- Android PackageManagerService详细分析
- 设置 webkit 背景透明的几种办法
- post提交和get提交的区别
- Ajax检测注册用户是否存在
- hibernate 总结
- 认清事实,看清真相,利剑苍穹,奋勇富强