class << self idiom

S

surge

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

Daniel DeLorme

surge said:
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?

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
 
S

surge

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

Surge
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,088
Latest member
JeremyMedl

Latest Threads

Top