Ruby在外行中的表现?

什么时候Ruby自我引用了Object,什么时候自我引用Ruby类? 用例子解释会很棒。 没有理解这个。

类实际上是对象本身。 可以说我有一个Person类,这实际上是Class一个实例。 所以你可以自己引用一个Article的实例,或者你可以自己引用类的实例, Article

在最简单的例子中,我可以想到:

 class Person def initialize p "Info about Person Instance" p self p self.class end p "Info about Person Class" p self p self.class end person = Person.new 

它打印:

 "Info about Person Class" Person Class "Info about Person Instance" # Person 

要阅读有关自我的更多信息, 我强烈建议您阅读本文。

我可以尝试自己解释一下,但我认为Yehuda Katz比我做得更好:

Ruby中的元编程:它是关于自我的全部

我的理解是

  • 在您定义类方法或module_functions的环境中, self指的是类/模块。
  • 在您定义实例方法的环境中, self指的是实例。

例如,

 class A def method1 self # => instance of A end def self.method2 self # => class A endu def A.method3 self # => class A end end class << A def method4 self # => class A end end module B module_function def method5 self # => module B end end 

例外情况是instance_evalinstance_exec self改为接收者。