about instance_eval

K

Kyung won Cheon

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^^
 
M

Mike Gold

Kyung said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top