about instance_eval

Discussion in 'Ruby' started by Kyung won Cheon, Nov 11, 2008.

  1. 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^^
    --
    Posted via http://www.ruby-forum.com/.
    Kyung won Cheon, Nov 11, 2008
    #1
    1. Advertising

  2. Kyung won Cheon

    Mike Gold Guest

    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.

    --
    Posted via http://www.ruby-forum.com/.
    Mike Gold, Nov 11, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    1
    Views:
    97
    Mauricio Fernández
    Jul 17, 2003
  2. Tim Bates

    instance_eval and Class Variables

    Tim Bates, Aug 6, 2003, in forum: Ruby
    Replies:
    0
    Views:
    110
    Tim Bates
    Aug 6, 2003
  3. Aron Griffis

    instance_eval and constants

    Aron Griffis, Feb 24, 2004, in forum: Ruby
    Replies:
    2
    Views:
    90
    Aron Griffis
    Feb 24, 2004
  4. Joel VanderWerf

    instance_eval from C ext

    Joel VanderWerf, Apr 26, 2004, in forum: Ruby
    Replies:
    3
    Views:
    186
    Joel VanderWerf
    May 3, 2004
  5. lopex

    instance_eval

    lopex, Aug 17, 2004, in forum: Ruby
    Replies:
    10
    Views:
    197
    Richard Dale
    Aug 17, 2004
Loading...

Share This Page