Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > about instance_eval

Reply
Thread Tools

about instance_eval

 
 
Kyung won Cheon
Guest
Posts: n/a
 
      11-11-2008
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^^
--
Posted via http://www.ruby-forum.com/.

 
Reply With Quote
 
 
 
 
Mike Gold
Guest
Posts: n/a
 
      11-11-2008
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.

--
Posted via http://www.ruby-forum.com/.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
instance_eval lopex Ruby 10 08-17-2004 03:27 PM
instance_eval from C ext Joel VanderWerf Ruby 3 05-02-2004 11:00 PM
instance_eval and constants Aron Griffis Ruby 2 02-24-2004 11:15 PM
instance_eval and Class Variables Tim Bates Ruby 0 08-06-2003 06:05 AM
instance_eval("class") error/bug??? walter@mwsewall.com Ruby 1 07-17-2003 05:29 PM



Advertisments