instance_eval

Discussion in 'Ruby' started by Srdjan Marinovic, Sep 11, 2006.

  1. hi,

    I've got a following problem: when I do

    instance_eval do
    class T
    end
    end

    (i'm doing this in irb, so self is main)

    everything is fine, I get a new class T.
    However when I do

    instance_eval "class T; end"

    I do not get a new class T. even though no errors were reported. Is
    there any particular reason for this?

    Thanks in advance

    srdjan
     
    Srdjan Marinovic, Sep 11, 2006
    #1
    1. Advertising

  2. Srdjan Marinovic

    ts Guest

    >>>>> "S" == Srdjan Marinovic <> writes:


    Try this

    S> instance_eval "class T; end"

    p class << self; T end


    Guy Decoux
     
    ts, Sep 11, 2006
    #2
    1. Advertising

  3. Srdjan Marinovic wrote:
    > I've got a following problem: when I do
    >
    > instance_eval do
    > class T
    > end
    > end


    This works because the context of the block is used to create T.

    > (i'm doing this in irb, so self is main)
    >
    > everything is fine, I get a new class T.
    > However when I do
    >
    > instance_eval "class T; end"
    >
    > I do not get a new class T. even though no errors were reported. Is
    > there any particular reason for this?


    T is nested into the singleton class of main, you could use
    instance_eval "class ::T; end"
    to create a top level class.

    But I don't understand why you use instance_eval, why not just eval?

    --
    Florian Frank
     
    Florian Frank, Sep 11, 2006
    #3
  4. hi,

    of course eval, I just didn't think of it really, I feel kinda silly:)
    Cheers for the explanation I didn't realise that T would be nested
    into the main.

    Thanks a lot

    srdjan
     
    Srdjan Marinovic, Sep 11, 2006
    #4
    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:
    103
    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:
    115
    Tim Bates
    Aug 6, 2003
  3. Aron Griffis

    instance_eval and constants

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

    instance_eval from C ext

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

    instance_eval

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

Share This Page