About searching constant


#1

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

###############


#2

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


#3

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.


#4

Kyung won Cheon wrote:

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.


#5

Bernardo Rufino wrote:

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)


#6

Mike G. wrote:

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.

You must be inside “class
A” (or “module A”) to get the constant lookup of WHY == A::WHY.

I understand it now…

Thank you!!