2

My understanding is that:

class Example
  class << self
    def my_method; end
  end
end

is equivalent to:

class Example
  def self.my_method; end
end

but is that correct?

ivan
  • 6,032
  • 9
  • 42
  • 65
  • 1
    Yes, that is correct :) – Magnuss Apr 15 '14 at 17:22
  • 2
    One important (but rarely needed) distinction is that you can define private methods using the `class << self` syntax. – Zach Kemp Apr 15 '14 at 17:26
  • Possible dup of [this](http://stackoverflow.com/questions/10964081/class-self-vs-self-method-with-ruby-whats-better), where some interesting points are made. Note you will need #1 for `attr_accessor :a`, for the class instance variable `@a`. You could replace `class << self` with `instance_eval do`. – Cary Swoveland Apr 15 '14 at 17:51

3 Answers3

3

They are equivalent, but choose the latter for clarity reasons. When you have a class that is many lines long you may miss the class method definition when using class << self.

kreek
  • 8,774
  • 8
  • 44
  • 69
2

Another good reason to use class << self is when you need accessors on the class level:

class Foo
  class << self
    attr_accessor :bar
  end
end

Beware that this is often not what you want as it is not thread safe. But that's a design problem. If you need it, you need it.

Lasse Skindstad Ebert
  • 3,370
  • 2
  • 29
  • 28
1

In the case of class << self all methods defined below will be class methods up until the class << self is closed. For a class method at a singular level or multiple ones if you wish you can define the method as self.foo.

class Test
    def self.foo
    end

    def bar
    end
end

class Test
    class << self
        def foo
        end
    end
    def bar
    end 
end

In both of these cases you will end up with a class method "foo" and an instance method "bar". Both ways accomplish the same thing.

user3206627
  • 39
  • 1
  • 6