理解ruby核心概念:Object, Class, Module, Kernel
- 关于Class:
Class的官方文档url:http://corelib.rubyonrails.org/classes/Class.html
(虽然《Programming Ruby 中文版第二版》翻译的已经算是不错了,但是在后面内置类库的一些译法上,我认为有可商榷之处。当我遇到书中有些话不能理解的时候,我会直接到ruby的网站上去看官方的英文文档。)
- Parent: Module
说明:请注意,Class是Module的子类。
在irb中运行:
Class.ancestors
输出:
=> [Class, Module, Object, Kernel]
运行:
Module.ancestors
输出:
=> [Module, Object, Kernel]
运行:
Object.ancestors
输出:
=> [Object, Kernel]
运行:
Kernel.ancestors
输出:
=> [Kernel]
- 其中Class, Module, Object 都是class,而Kernel是Module。
- Object mixes in the Kernel module, making the built-in kernel functions globally accessible. Although the instance methods of Object are defined by the Kernel module, we have chosen to document them here for clarity.
- Object混入了Kernel这个模块,又由于Object是Ruby中所有类的父类,这样以来,Kernel中内建的核心函数就可以被Ruby中所有的类和对象访问。
- Object的实例方法由Kernel模块定义。
- Kernel模块中定义了private method和public method
- 对于一个普通的对象,可以直接调用Kernel的public method
- 在irb中运行: a=Object.new
输出:=> #<Object:0x2ee9470>
- 运行: a.public_methods
输出:
=> ["inspect", "clone", "public_methods", "display", "instance_variable_defined?", "equal?", "freeze", "methods", "respond_to?", "dup", "to_yaml_style",
"instance_variables", "__id__", "method", "eql?", "id", "singleton_methods", "send", "taint", "to_yaml_properties", "frozen?", "instance_variable_get", "__send__", "instance_of?", "to_a", "to_yaml", "type", "protected_methods", "instance_eval", "object_id", "require_gem", "==", "require", "===", "taguri", "instance_variable_set", "kind_of?", "extend", "gem", "to_s", "taguri=", "hash", "class", "private_methods", "=~", "tainted?", "untaint", "nil?", "is_a?"]
- 而要想调用一个普通对象所包含的Kernel的函数,用一般的调用方法无法做到,只有通过Send来实现:
发表评论
- 浏览: 15852 次

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
初次实践user story时遇到 ...
bryanzk 写道hgq0011 写道你们都会有一个好的平台给你们练习或者有一 ...
-- by hgq0011 -
初次实践user story时遇到 ...
一个合格的“客户”应该是什么样的? 首先是要明确自己的商业价值,为了实现这个商业 ...
-- by lane_cn -
初次实践user story时遇到 ...
excel...
-- by snomile -
初次实践user story时遇到 ...
basicbest 写道gigix 写道ozzzzzz 写道use story如 ...
-- by gigix -
初次实践user story时遇到 ...
gigix 写道ozzzzzz 写道use story如果复杂到你写的那个地步, ...
-- by basicbest






评论排行榜