开发者

Ruby: What does class << self do? [duplicate]

This question already has answers here: class << self idiom in Ruby (6 answers) Closed 8 years ago.
class Person
  class << self
    def species
      "Homo Sapien"
    end
  end
end

Why do i need to use class << self ?

What's the ben开发者_高级运维efit ? Why do i need it?


Any method declared inside class << self will be defined on the class instance, not instances of the class. In the example above, you'll be able to call Person.species but not Person.new.species.


class << obj provides you access to metaclass (also known as eigenclass or singleton class) of obj, everything within that construction is executed in context of that metaclass. self directly in class definition references that class, so in your example, method species is defined as class method on Person.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜