Forum: Ruby about searching constant

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kyung won C. (Guest)
on 2008-12-31 16:21
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^^
###############
Bernardo R. (Guest)
on 2009-01-01 09:10
(Received via mailing list)
Weird, if you use A.instance_eval("self::WHY") it simply works... can
anyone
explain it?
Brian C. (Guest)
on 2009-01-01 10:57
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.
Mike G. (Guest)
on 2009-01-02 11:27
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.
Brian C. (Guest)
on 2009-01-02 16:56
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)
Kyung won C. (Guest)
on 2009-01-05 03:35
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!!
This topic is locked and can not be replied to.