# Class \<\< self idiom

**URL:** <https://www.ruby-forum.com/t/class-self-idiom/107374>\
**Category:** Ruby\
**Created:** [June 20, 2007, 11:40pm UTC](https://www.ruby-forum.com/t/class-self-idiom/107374 "2007-06-20T23:40:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![surge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/4da419/32.png) [@surge](https://www.ruby-forum.com/u/surge)\
**Post date:** [June 20, 2007, 11:40pm UTC](https://www.ruby-forum.com/t/class-self-idiom/107374/1 "2007-06-20T23:40:49Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![surge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/4da419/32.png) [@surge](https://www.ruby-forum.com/u/surge)\
**Post date:** [June 21, 2007, 12:56am UTC](https://www.ruby-forum.com/t/class-self-idiom/107374/2 "2007-06-21T00:56:56Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![surge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/4da419/32.png) [@surge](https://www.ruby-forum.com/u/surge)\
**Post date:** [June 21, 2007, 1:21am UTC](https://www.ruby-forum.com/t/class-self-idiom/107374/3 "2007-06-21T01:21:59Z")

</div>

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

Surge
