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^^
###############
--
Posted via http://www.ruby-forum.com/.
Weird, if you use A.instance_eval("self::WHY") it simply works... can anyone
explain it?
···
On Wed, Dec 31, 2008 at 12:20 PM, Kyung won Cheon <kdream95@gmerce.co.kr>wrote:
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^^
###############
--
Posted via http://www.ruby-forum.com/\.
--
Bernardo Rufino
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?
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.
···
--
Posted via http://www.ruby-forum.com/\.
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.
···
--
Posted via http://www.ruby-forum.com/.
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)
···
--
Posted via http://www.ruby-forum.com/\.