# About instance\_eval

**URL:** <https://www.ruby-forum.com/t/about-instance-eval/153050>\
**Category:** Ruby\
**Created:** [November 11, 2008, 3:51pm UTC](https://www.ruby-forum.com/t/about-instance-eval/153050 "2008-11-11T15:51:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kyung\_won\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/47e85d/32.png) [@Kyung\_won\_C](https://www.ruby-forum.com/u/Kyung_won_C)\
**Post date:** [November 11, 2008, 3:51pm UTC](https://www.ruby-forum.com/t/about-instance-eval/153050/1 "2008-11-11T15:51:51Z")

</div>

class A  
WHY = “I don’t know why!!”

def self.foo  
WHY  
end  
end

puts A.instance\_eval(“foo”) # =\> I don’t know why!!  
puts A.instance\_eval(“WHY”) # =\> uninitialized constant Class::WHY  
(NameError)

# What’s difference?

# Help Me^^

---

<div class="post-metadata">

**Author:** ![Kyung\_won\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/47e85d/32.png) [@Kyung\_won\_C](https://www.ruby-forum.com/u/Kyung_won_C)\
**Post date:** [November 11, 2008, 4:37pm UTC](https://www.ruby-forum.com/t/about-instance-eval/153050/2 "2008-11-11T16:37:59Z")

</div>

Kyung won Cheon wrote:

> class A  
> WHY = “I don’t know why!!”
> 
> def self.foo  
> WHY  
> end  
> end
> 
> puts A.instance\_eval(“foo”) # =\> I don’t know why!!  
> puts A.instance\_eval(“WHY”) # =\> uninitialized constant Class::WHY  
> (NameError)
> 
> # What’s difference?
> 
> # Help Me^^

A.instance\_eval { foo } # =\> “I don’t know why!!”  
A.instance\_eval { constants } # =\> [“WHY”]  
A.instance\_eval { const\_get “WHY” } # =\> “I don’t know why!!”  
class A ; eval “WHY” ; end # =\> “I don’t know why!!”

Constants follow different rules for lookup.

instance\_eval changes the ‘self’ for method lookups, but you are still  
in the top-level scope for constant lookups. You must be inside “class  
A” (or “module A”) to get the constant lookup of WHY == A::WHY.

Note the complementary case,

B = Class.new {  
WHEREAMI = “here”  
}

WHEREAMI # =\> “here”

Despite being defined inside the instance of B, this constant lies in  
the top-level scope.
