首页 > 解决方案 > Ruby 中的 `class Foo < self` 有什么作用?

问题描述

通过查看 redis-store RubyGem 的源代码,我偶然发现了这种我以前从未见过的语法:

class Foo < self
  # ...
end

我的 Google-Fu 显然不够强大,因为我找不到任何描述它的作用的东西。

这会以某种方式重新打开 Foo,将其自身扩展为超类,从而可以覆盖可以将原始定义称为super. 我接近了吗?

标签: ruby

解决方案


class Foo < Bar
end

是如何告诉 RubyFoo继承自Bar.

在类定义中,self指的是类本身:

# prints Foo
class Foo
  puts self
end

所以

class Foo
  class Bar < self
  end
end

只是说它Bar嵌套在下面Foo并继承自它。


推荐阅读