Class << self idiom


#1

Hello,

I have trouble understanding the need for the class << self idiom. For
example, let’s say I have this class:

class My_Class
def method_1
end
end

Now, I want to extend that class. I can do:

class My_Class
def method_2
end
end

or:

class My_Class
class << self
def method_2
end
end
end

I understand that in the second case we’re extending the singleton
class of My_Class, but why is the second form so often used in Ruby
vs. the other form? Isn’t the end result identical?


#2

surge wrote:

class << self
def method_2
end
end
end

I understand that in the second case we’re extending the singleton
class of My_Class, but why is the second form so often used in Ruby
vs. the other form? Isn’t the end result identical?

They are not identical. The first defines an instance method
(My_Class.new.method_2); the second defines a class method
(My_Class.method_2

Now, there are other ways of defining class methods. Which one you use
depends a lot on personal preference but depends also on constants
(which have a static scope) ->

class Foo
K = “foo”
end

#can access K
class Foo
class << self
def foo1; K; end
end
def self.foo2; K; end
def Foo.foo3; K; end
end

#must specify Foo::K
class << Foo
def foo4; Foo::K; end
end
def Foo.foo5; Foo::K; end

Daniel


#3

You’re completely right and I understand my mistake now. Thanks for
the comprehensive answer.

Surge