关于Ruby中的类定义

最近,我正在研究关于Ruby类的一些细节,并且被类定义弄糊涂了。

在Ruby中,类的定义如下,

class A
    def self.my_method
    end
end

和它一样

class A
    class << self
        def my_method
        end
    end
end

然后我很困惑。 对于第一种情况,self可以被看作是当前使用对象的指针,而当前上下文的类是A.并且递归地执行查找方法。 但我的问题是, def做什么? 它如何改变当前的对象和上下文? 第二种情况的问题是一样的。 像类“自我 ”这样的描述如何改变当前的对象和上下文?

还有一个问题。 据我所知,所有的Class对象都遵循像fly-weight这样的设计模式,因为它们共享具有相同定义的同一个Class对象。 然后特征类变得混乱。 由于本征类中的def实际上定义了一个带有Class对象的方法,它如何与“def self。*”相关?

它看起来太复杂了,我可能需要Ruby的设计细节。


class A
  # self here is A
  def aa
    # self here is the instance of A who called this method
  end
  class << self
    # self is the eigenclass of A, a pseudo-class to store methods to a object.
    # Any object can have an eigenclass.
    def aa
      # self is the pseudo-instance of the eigenclass, self is A.
    end
  end
end

这是一样的:

class A
  def self.aa
  end
end

和这个:

class << A
  def aa
  end
end

而且这也是:

def A.aa
end

你可以打开任何东西的特征类:

hello = "hello"
class << hello
  def world
    self << " world"
  end
end
hello.world #=> "hello world"
"my".world  #=> NoMethodError

一个特征类实际上是一个类的实例,它也有它自己的特征类。

“如果它看起来太混乱了,只记得Class是一个对象,而Object是一个类。”

链接地址: http://www.djcxy.com/p/95431.html

上一篇: About class definition in Ruby

下一篇: Ruby operator method calls vs. normal method calls