惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
美团技术团队
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
有赞技术团队
有赞技术团队
GbyAI
GbyAI
宝玉的分享
宝玉的分享
腾讯CDC
M
MIT News - Artificial intelligence
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
月光博客
月光博客
MyScale Blog
MyScale Blog
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog

博客园 - 小熊bryan

坐视——做事——做势 InfoQ中文站正式升级为1.5版 编辑絮语 今年…… 书店的风景 要敏捷一点,再敏捷一点 对Ruby中Kernel的callcc方法的研究 再试试看 越来越觉得自己的博客像个包子 翻译作品:为敏捷团队设计协作空间 用元编程的方式向Ruby添加properties 【翻译】在ruby中实现attributes的lazily initialization(惰性初始化) 《Programming Ruby 中文版第二版》P577页singleton_method_undefined方法说明有点问题 是没有好音乐,还是我们没有好心境? Best of Ruby Quiz 之四 Animal Quiz之我的答案 Best of Ruby Quiz 笔记之三:GEDCOM Parser 使用REXML在ruby中处理xml 软件的业务价值来自哪里?——business value generally comes from using software 要问五次为什么--业务需求挖掘之道(摘自Wikipedia)
理解ruby核心概念:Object, Class, Module, Kernel
小熊bryan · 2007-08-07 · via 博客园 - 小熊bryan
        

作为一个Ruby初学者,最让我感到头痛的就是ProcClassModuleKernelObject这几者之间的关系,如果能把他们搞懂,并且可以玩弄于股掌之间的话,感觉这样才算是真正进了Ruby的大门。本文记录我在学习并感受这几个类时的点点滴滴。

  • 关于Class

         Class的官方文档urlhttp://corelib.rubyonrails.org/classes/Class.html

(虽然《Programming Ruby 中文版第二版》翻译的已经算是不错了,但是在后面内置类库的一些译法上,我认为有可商榷之处。当我遇到书中有些话不能理解的时候,我会直接到ruby的网站上去看官方的英文文档。)

    •  Parent: Module

说明:请注意,ClassModule的子类。

irb中运行:

Class.ancestors

输出:

=> [Class, Module, Object, Kernel]

运行:

Module.ancestors

输出:

=> [Module, Object, Kernel]

运行:

Object.ancestors

输出:

=> [Object, Kernel]

运行:

Kernel.ancestors

输出:

=> [Kernel]

  • 其中Class, Module, Object 都是class,KernelModule
  • 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这个模块,又由于ObjectRuby中所有类的父类,这样以来,Kernel中内建的核心函数就可以被Ruby中所有的类和对象访问。
  • Object的实例方法由Kernel模块定义。
  • Kernel模块中定义了private methodpublic method
    • 对于一个普通的对象,可以直接调用Kernelpublic 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来实现: