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?
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?
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
.
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.
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.