Ruby 笔记:匿名类/单例类/元类/特征类 的 5 中声明方式

Mark24 · 2021年09月18日 · 382 次阅读

一个匿名类(Anonymous Class)也被称作单例类(Singleton Class),特征类(Eigenclass),鬼魂类(Ghost Class),元类(Metaclass)或者 uniclass。

Ruby 中每个对象都有其自己的匿名类,一个类能拥有方法,但是只能对该对象本身其作用:当我们对一个具体的对象添加方法时,Ruby 会插入一个新的匿名类于父类之间,来容纳这个新建立的方法。值得注意的是,匿名类通常是不可见(Hidden)的。它没有名字因此不能像其他类一样,通过一个常量来访问。你不能为这个匿名类实例化一个新的对象。

下面展示了建立匿名类的一些方法:


# 1
class Rubyist
  def self.who
    "Geek"
  end
end

# 2
class Rubyist
  class << self
    def who
      "Geek"
    end
  end
end

# 3
class Rubyist
end
def Rubyist.who
  "Geek"
end

#4
class Rubyist
end
Rubyist.instance_eval do
  def who
    "Geek"
  end
end
puts Rubyist.who # => Geek

# 5
class << Rubyist
  def who
    "Geek"
  end
end

上述 5 段代码,分别定义了 Rubylist.who 方法,该方法返回"Geek"。

任何时候,一旦你看到如上述标号为#5 的代码,class 关键字后面紧接着<<,你就应该确信这里为<<右边的对象打开了一个匿名类。

[BLOG](https://mark24code.github.io/ruby/2021/09/18/Ruby%E4%B8%AD%E5%8D%95%E4%BE%8B%E7%B1%BB%E7%9A%845%E7%A7%8D%E5%A3%B0%E6%98%8E%E6%96%B9%E5%BC%8F.html

来源

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号