理解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来实现: