随笔-36  评论-26  文章-0  trackbacks-1

理解ruby核心概念:Object, Class, Module, Kernel

        作为一个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来实现:

 

posted on 2007-08-07 13:05 小熊bryan 阅读(426) 评论(0) 编辑 收藏
我的文章用到的缩略语列表:
  • CI/ci = 持续集成
  • TD.net/td.net = TestDriven.net
  • cc.net/CC.NET = CruiseControl.net
  • TM/TM.net = TypeMock.net
  • UE/ue = ultraedit
  • ROR/ror=Ruby On Rails
联系方式:
SMN: bryanzk@hotmail.com MAIL:bryanzk@gmail.com
Subscribe by Anothr订阅到MSN/Skype/Gtalk
    我的豆瓣:

    昵称:小熊bryan
    园龄:4年9个月
    粉丝:0
    关注:0
    <2007年8月>
    2930311234
    567891011
    12131415161718
    19202122232425
    2627282930311
    2345678

    搜索

     
     

    常用链接

    随笔分类(75)

    随笔档案(38)

    最新评论

    阅读排行榜

    评论排行榜

    推荐排行榜