Ruby: What does class << self do? [duplicate]
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.
加载中,请稍侯......
精彩评论