# Instance\_eval

**URL:** <https://www.ruby-forum.com/t/instance-eval/68281>\
**Category:** Ruby\
**Created:** [September 11, 2006, 1:03pm UTC](https://www.ruby-forum.com/t/instance-eval/68281 "2006-09-11T13:03:59Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Srdjan\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dec6dc/32.png) [@Srdjan\_M](https://www.ruby-forum.com/u/Srdjan_M)\
**Post date:** [September 11, 2006, 1:03pm UTC](https://www.ruby-forum.com/t/instance-eval/68281/1 "2006-09-11T13:03:59Z")

</div>

hi,

I’ve got a following problem: when I do

instance\_eval do  
class T  
end  
end

(i’m doing this in irb, so self is main)

everything is fine, I get a new class T.  
However when I do

instance\_eval “class T; end”

I do not get a new class T. even though no errors were reported. Is  
there any particular reason for this?

Thanks in advance

srdjan

---

<div class="post-metadata">

**Author:** ![Srdjan\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dec6dc/32.png) [@Srdjan\_M](https://www.ruby-forum.com/u/Srdjan_M)\
**Post date:** [September 11, 2006, 1:20pm UTC](https://www.ruby-forum.com/t/instance-eval/68281/2 "2006-09-11T13:20:01Z")

</div>

> > > > > “S” == Srdjan M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) writes:

Try this

S\> instance\_eval “class T; end”

p class \<\< self; T end

Guy Decoux

---

<div class="post-metadata">

**Author:** ![Srdjan\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dec6dc/32.png) [@Srdjan\_M](https://www.ruby-forum.com/u/Srdjan_M)\
**Post date:** [September 11, 2006, 1:38pm UTC](https://www.ruby-forum.com/t/instance-eval/68281/3 "2006-09-11T13:38:04Z")

</div>

Srdjan M. wrote:

> I’ve got a following problem: when I do
> 
> instance\_eval do  
> class T  
> end  
> end

This works because the context of the block is used to create T.

> (i’m doing this in irb, so self is main)
> 
> everything is fine, I get a new class T.  
> However when I do
> 
> instance\_eval “class T; end”
> 
> I do not get a new class T. even though no errors were reported. Is  
> there any particular reason for this?

T is nested into the singleton class of main, you could use  
instance\_eval “class ::T; end”  
to create a top level class.

But I don’t understand why you use instance\_eval, why not just eval?

---

<div class="post-metadata">

**Author:** ![Srdjan\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dec6dc/32.png) [@Srdjan\_M](https://www.ruby-forum.com/u/Srdjan_M)\
**Post date:** [September 11, 2006, 1:46pm UTC](https://www.ruby-forum.com/t/instance-eval/68281/4 "2006-09-11T13:46:04Z")

</div>

hi,

of course eval, I just didn’t think of it really, I feel kinda silly:)  
Cheers for the explanation I didn’t realise that T would be nested  
into the main.

Thanks a lot

srdjan
