# Metaclass/Singleton class question

**URL:** <https://www.ruby-forum.com/t/metaclass-singleton-class-question/151840>\
**Category:** Rails\
**Created:** [October 26, 2008, 7:30pm UTC](https://www.ruby-forum.com/t/metaclass-singleton-class-question/151840 "2008-10-26T19:30:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![joe-black](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/87869e/32.png) [@joe-black](https://www.ruby-forum.com/u/joe-black)\
**Post date:** [October 26, 2008, 7:30pm UTC](https://www.ruby-forum.com/t/metaclass-singleton-class-question/151840/1 "2008-10-26T19:30:27Z")

</div>

I understand that (class \<\< self; self; end) returns the singelton class  
of object that is calling it but why would use that instead of self \<\<  
MyClass …?

For example, arent these all equivalent?

class \<\< String  
def foo  
puts “foo”  
end  
end

class String  
class \<\< self  
def foo  
puts “foo”  
end  
end  
end

class String  
(class \<\< self; self; end).module\_eval do  
def foo  
puts “foo”  
end  
end  
end

So why would you use the more obscure (class \<\< self; self; end)  
technique? Can someone please explain.

---

<div class="post-metadata">

**Author:** ![joe-black](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/87869e/32.png) [@joe-black](https://www.ruby-forum.com/u/joe-black)\
**Post date:** [October 26, 2008, 8:02pm UTC](https://www.ruby-forum.com/t/metaclass-singleton-class-question/151840/2 "2008-10-26T20:02:37Z")

</div>

On 26 Oct 2008, at 18:30, Joe B. wrote:

> puts “foo”
> 
> class String  
> (class \<\< self; self; end).module\_eval do  
> def foo  
> puts “foo”  
> end  
> end  
> end
> 
> So why would you use the more obscure (class \<\< self; self; end)  
> technique? Can someone please explain.

if self isn’t a class for example

class Object  
def meta  
(class \<\< self; self; end)  
end  
end

x = “123”  
x.meta.module\_eval do  
def foo  
puts “foo”  
end  
end

x.foo

you could of course have just done

def x.foo  
puts “foo”  
end

but sometimes you want to more than just add a method.

Fred
