【问题标题】:About class definition in Ruby关于 Ruby 中的类定义
【发布时间】:2011-12-16 09:35:13
【问题描述】:

最近,我在研究 Ruby 中类的一些细节,对类的定义感到困惑。

在Ruby中,类定义如下,

class A
    def self.my_method
    end
end

和它一样

class A
    class << self
        def my_method
        end
    end
end

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

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

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

【问题讨论】:

  • 实际上我并没有让您感到困惑... self 是单例类实例,因此def self.foobar 声明了一个类方法,而def foobar 声明了一个实例方法,其中 self 是当前实例。至于你的情况......他们不应该是一样的吗? (您正在声明类方法)

标签: ruby class metaclass eigenclass


【解决方案1】:
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 是一个类。”

【讨论】:

  • 最后一句话启发了我。谢谢!
猜你喜欢
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 2011-01-04
  • 2016-06-30
  • 1970-01-01
相关资源
最近更新 更多