Ruby:对象模型(又称八卦模型)笔记
2013-09-12 09:01
246 查看
备注
如果说哪门语言对我影响最大,那就是Ruby了,在.NET阵营多年,试图去用C#的思维去解释很多东西,当然解释Java是足够了,可惜我也用了好几年去解释Javascript,结果是可想而知的:解释不通。直到我遇到Ruby,这让我了解到一件事:不能用一种语言的思维去解释另外一种语言,当然某些局部特点是有可比性的。本文重点解释一下Ruby的对象模型(可以理解我Javascript的原型模型),有此可以看出Ruby的完美和统一。
对象模型
无图无真相
基本规则
一切皆为对象:instance是一般对象、#instance是临时类型对象、Child是一般类型对象、Class是特殊的元类型对象(其实例是一般类型对象)、Mixinable是一般模块对象、Module是元模块对象(其实例是一般模块对象)。只有实例方法,即方法只能定义在类型上(不像Javascript,可以存储在对象上),即:如果 xxx.class = Class or xxx.class = Module 那么 xxx 可以定义实例方法。
所有实例变量只存储在对象自身上(不像Javascript,可以存储在原型链的任何位置)。
所有类型都可以在任何时候进行修改(Open Class)。
instance.method的查找规则:先查看singleton class,然后递归遍历所有super class和Mixed Module,遇到第一个即返回,这个过程也叫:右移一步,然后向上。
代码示例
# coding: utf-8 class Parent def hi() puts "hi" end end module Mixinable def hey() puts "hey" end end class Child < Parent include Mixinable def hello() puts "hello" end end instance = Child.new instance.hello instance.hey instance.hi
如何修改Singleton Class?
第一种方式class << instance def instance_singleton_method_one puts "instance_singleton_method_one" end end instance.instance_singleton_method_one
第二种形式
def instance.instance_singleton_method_two puts "instance_singleton_method_two" end instance.instance_singleton_method_two
如何修改类型,如Child?
注意:下面演示的是“Open Class”,不是重新定义一个类型。class Child def child_method_one() puts "child_method_one" end end instance.child_method_one
类型方法是特殊的实例方法,这些方法定义在类型的Singleton Class中。
第一种方式class Child def Child.child_class_method_one() puts "child_class_method_one" end end Child.child_class_method_one
第二种形式
class Child def self.child_class_method_two() puts "child_class_method_two" end end Child.child_class_method_two
第三种形式
def Child.child_class_method_three puts "child_class_method_three" end Child.child_class_method_three
第四种形式
class << Child def child_class_method_four() puts "child_class_method_four" end end Child.child_class_method_four
备注
图中很多关系有兴趣的朋友可以自己验证,本文没有涉及元编程,元编程不过是按照一定的元数据来修改类型定义或生成类型定义,也就是说元编程的前提是类型可以动态的修改,了解了本文,元编程不在话下。相关文章推荐
- ruby学习笔记之【对象模型】
- 深入探索C++对象模型笔记一 —— 关于对象(上)
- 深入探索C++对象模型笔记之四 —— 构造函数语意学 (Copy Constructor的建构操作)
- 《深度探索C++对象模型(Inside The C++ Object Model )》学习笔记
- [学习笔记]Java面向对象思想和内存模型
- C++对象模型笔记:概述
- C++对象模型笔记(一) C++对象
- C++对象模型笔记:对象的三种内存布局
- C++对象模型-笔记二
- Ruby对象模型小结
- Ruby元编程-学习笔记(一)-对象模型
- 深度探究C++对象模型第0章笔记
- 《深度探索C++对象模型(Inside The C++ Object Model )》学习笔记
- 深入探索C++对象模型笔记之五 —— 构造函数语意学 (成员们的初始化队伍 Member Initialization List)
- Thinking in UML 学习笔记(一)——建立对象模型
- C++对象模型笔记:对象的三种内存布局
- 《深度探索C++对象模型(Inside The C++ Object Model )》学习笔记
- Sharepoint学习笔记—ECMAScript对象模型系列-- 6、使用ECMA操作列表项对象(list item)
- 深入探索C++对象模型笔记1
- qutecom笔记-模型-PhoneCall对象