# Ruby元程序就是关于Self :It’s All About the Self # 所有ruby代码在ruby代码执行的过程中,是没有没有单独的编译或运行阶段. 在Ruby中,每一行代码是对一个特定对象的执行的 =begin 一个匿名类(Anonymous Class)也被称作单例类(Singleton Class),特征类(Eigenclass),鬼魂类(Ghost Class), 元类(Metaclass)或者 uniclass译名请求. Eigenclass: an object’s own class Metaclass: the class of a class =end # 每个对象都有一个它自己的独有的,隐藏的类。它被叫做: 那个对象的 eigen-class. =begin eigenclass的作用域: class << an_object # your code that end 如果你想得到一个eigenclass的引用,你可以在外部域返回一个self,例如: obj = Object.new eigenclass = class << obj self end > eigenclass => #<Class:#<Object:0x2bccd0>> > eigenclass.class => Class =end # 一个对象的Eigenclass 是其单例方法保存的地方 =begin Eigenclasses and instance_eval() instance_eval():改变的是the current class类的Eigenclass. Eigenclasses and Method lookup(lookup具体详见:方法调用) Eigenclasses位于方法查找的最底端,也就是说, 最先开始方法查找的地方就是这个对象自己的Eigenclass. =end # 目前为止我们可以编写一下五种方式,创建类方法: #1 class Person def self.ni_ming_lei "this is a ni_ming_lei" end end #2 class Person class << self def ni_ming_lei "this is a ni_ming_lei" end end end #3 class << Person def ni_ming_lei "this is a ni_ming_lei" end end #4 Person.instance_eval do def ni_ming_lei "this is a ni_ming_lei" end end # 5 class Person end def Person.ni_ming_lei "this is a ni_ming_lei" end # 方法调用: p Person.ni_ming_lei # =>"this is a ni_ming_lei" # 至于使用那种看自己的习惯了~~~ # 我们知道eigenclass也是一个类,它也是一个对象,故而他也有自己的eigenclass。貌似极为少见。。。。 # 类的实例方法的书写 class Per def name "Test" end end Per.class_eval do def name "Matz" end end p Per.new.name #>"Matz"
# 作用域 # 在下面的表格,定义一个新的范围他的意思是指块内的代码没有权限对外部块的局部变量的访问。
mechanism | method resolution | method definition | new scope? | |
---|---|---|---|---|
class Person | Person | same | yes | |
class << Person | Person’s metaclass | same | yes | |
Person.class_eval | Person | same | no | |
Person.instance_eval | Person | Person’s metaclass | no |