Forum: Ruby about instance_eval

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-11-11 16:51
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^^
Mike G. (Guest)
on 2008-11-11 17:37
Kyung won Cheon wrote:
> 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.
This topic is locked and can not be replied to.