about searching constant

K

Kyung won Cheon

class A
WHY = "I don't know why!!"

def self.foo
instance_eval("WHY")
end
end

puts A.instance_eval { foo } # => I don't know why!!
puts A.instance_eval("WHY") # => uninitialized constant Class::WHY
(NameError)

###############
# Help Me^^
###############
 
B

Bernardo Monteiro Rufino

[Note: parts of this message were removed to make it a legal post.]

Weird, if you use A.instance_eval("self::WHY") it simply works... can anyone
explain it?
 
B

Brian Candler

It also works if you change instance_eval to class_eval (or
module_eval).

However I'm not entirely sure of the difference between the former and
the latter two.
 
M

Mike Gold

Kyung said:
class A
WHY = "I don't know why!!"

Umm ... You already posted this question, and I answered it.
Did you not like the answer?

http://www.ruby-forum.com/topic/170583

Also as Brian mentioned, module_eval/class_eval works.

An invisible parameter is passed to a block (search for cases of
specific_eval in eval.c) which is used for constant lookups.

For A.module_eval { } and A.class_eval { }, that invisible parameter
is A. But for A.instance_eval { }, it is A's singleton class.

The constant lies in A, not in A's singleton class.
 
B

Brian Candler

Bernardo said:
Weird, if you use A.instance_eval("self::WHY") it simply works... can
anyone
explain it?

Because that's the same as A::WHY

(i.e. inside foo.instance_eval { ... }, self is foo)
 

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,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top