0

最近在研究 Ruby 中类的一些细节,被类定义弄糊涂了。

在Ruby中,类定义如下,

class A
    def self.my_method
    end
end

和它一样

class A
    class << self
        def my_method
        end
    end
end

然后我很困惑。对于第一种情况,self可以看成是一个指向当前使用对象的指针,上下文的当前类是A。方法查找是递归完成的。但我的问题是,def是做什么的?它如何改变当前对象和上下文?第二种情况的问题是一样的。class << self之类的描述如何改变当前对象和上下文?

还有一个问题。据我所知,所有 Class 对象都遵循 Fly-weight 等设计模式,因为它们共享具有相同定义的相同 Class 对象。然后特征类变得混乱。既然eigenclass中的def其实是用Class对象定义了一个方法,那怎么会和“def self.*”相关呢?

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

4

1 回答 1

4
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

eigenclass 实际上是 Class 的一个实例,它也有自己的 eigenclass。

“如果它看起来太令人困惑,请记住 Class 是一个对象,而 Object 是一个类。”

于 2011-10-27T18:04:37.533 回答