SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    Mlle. Ledoyen silver trophy seanf's Avatar
    Join Date
    Jan 2001
    Location
    UK
    Posts
    7,168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Create object instance using string value

    Hello,

    In Ruby is it possible to create an object instance using a string value? For example, in PHP the following is possible:

    PHP Code:
    <?php

        
    class SomeClass {

            function 
    __construct ( ) {

                echo 
    'Hello!';

            }  
    // End method

        
    }

        
    $class 'SomeClass';

        new 
    $class ( );

    ?>
    Sean
    Harry Potter

    -- You lived inside my world so softly
    -- Protected only by the kindness of your nature

  2. #2
    Mlle. Ledoyen silver trophy seanf's Avatar
    Join Date
    Jan 2001
    Location
    UK
    Posts
    7,168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Of course I post and then work it out! For those interested:

    Code:
    class_name = 'SomeClass'
    
    Object.const_get(class_name.classify).new
    Sean
    Harry Potter

    -- You lived inside my world so softly
    -- Protected only by the kindness of your nature

  3. #3
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    .classify is not neccesary (in fact it does nothing in this case):

    Code:
    class_name = 'SomeClass'
    Object.const_get(class_name).new
    But because classes are objects in Ruby it's better to do:

    Code:
    the_class = SomeClass
    the_class.new

  4. #4
    SitePoint Guru silver trophy Luke Redpath's Avatar
    Join Date
    Mar 2003
    Location
    London
    Posts
    794
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For convenience you could define a to_class() method on String:

    Code:
    class String
      def to_class
        Object.const_get(self)
      end
    end
    
    foo = "Foo".to_class.new

  5. #5
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is what eval is for
    Code:
    eval("Foo").new


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •