0
class Person
  class << self
    def species
      "Homo Sapien"
    end
  end
end

Why do i need to use class << self ?

What's the benefit ? Why do i need it?

newcomer
  • 81
  • 3
  • 6

2 Answers2

1

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.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • @newcomer, yes, like static methods in PHP/Java. – Dogbert Jul 25 '11 at 10:48
  • 1
    You can also write `def self.species`, as `self` refers to the class instance within the definition of a class. – hammar Jul 25 '11 at 10:58
  • You can also write `def Person.species`, ruby gives you lots of options as you can see. Personally, I prefer using `def self.species` as it is clear that `species` is a class method without having to scroll around, *unless* **all** the methods are indeed class methods, and than I would prefer `class << self`. – Jakobinsky Jul 25 '11 at 11:31
1

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.

Victor Deryagin
  • 11,895
  • 1
  • 29
  • 38