Create instance of class. Class name stored in a string.

Discussion in 'Ruby' started by shaw.cttk@gmail.com, Sep 25, 2012.

  1. Guest

    Hi, I'm super new in Ruby World, and got in trouble with that:

    how do I call the 'new' method of a class I don't know the name? The name of the class is stored in a string.

    something like:

    arg1 = "RADIUS"
    codec = arg1.new

    I would like to create an instance of whatever class name is stored in arg1 string.

    Thanks in advance.

    -- sfim
     
    , Sep 25, 2012
    #1
    1. Advertising

  2. On 25.09.2012 02:17, wrote:
    > Hi, I'm super new in Ruby World, and got in trouble with that:
    >
    > how do I call the 'new' method of a class I don't know the name? The
    > name of the class is stored in a string.
    >
    > something like:
    >
    > arg1 = "RADIUS" codec = arg1.new
    >
    > I would like to create an instance of whatever class name is stored
    > in arg1 string.


    The usual idiom which also works with nested names is like this:

    cls = name.split('::').inject(Object) {|cl, part| cl.const_get part}

    Now you can do

    obj = cls.new

    In your case it's sufficient to do

    cls = Object.const_get(arg1) # "RADIUS"
    codec = cls.new

    Kind regards

    robert

    --
    remember.guy do |as, often| as.you_can - without end
    http://blog.rubybestpractices.com/
     
    Robert Klemme, Sep 25, 2012
    #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. Islam Elkhayat

    Create 2 instance with the same name

    Islam Elkhayat, Mar 29, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    376
    Nick Malik [Microsoft]
    Mar 29, 2005
  2. Matt
    Replies:
    10
    Views:
    634
    Chris Smith
    Apr 7, 2004
  3. Sridhar R
    Replies:
    14
    Views:
    1,456
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  4. Sandra-24
    Replies:
    18
    Views:
    1,942
    Steve Holden
    Apr 29, 2006
  5. Martin P. Hellwig
    Replies:
    1
    Views:
    389
    Martin P. Hellwig
    Mar 26, 2010
Loading...

Share This Page