Forum: Ruby How to get a new instance of a class given a String

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.
Bd6167863690cb320d65bb9204619817?d=identicon&s=25 David Clements (Guest)
on 2006-05-03 18:59
(Received via mailing list)
Hey,

I know I have seen his on the list before but I can't seem to find it.

I want to do something like

class_name = "UserPreference"
up = Class.class_for_name(class_name).new

Anyone?

Also, where would be a good place for me to find a reference for all the
very useful methods for  Meta Programming?

Thanks,

Dave
9358cc96c46055cd68d4a76a9aefe026?d=identicon&s=25 Daniel Harple (Guest)
on 2006-05-03 18:59
(Received via mailing list)
On May 2, 2006, at 5:03 PM, David Clements wrote:

> class_name = "UserPreference"
> up = Class.class_for_name(class_name).new

up = Object.const_get(class_name).new

-- Daniel
9dfe8c734b0f9b37a4e218425c0a2138?d=identicon&s=25 gene.tani@gmail.com (Guest)
on 2006-05-03 18:59
(Received via mailing list)
Ced5fff44ff8929fc974012ea108b284?d=identicon&s=25 Sergey Volkov (Guest)
on 2006-05-03 18:59
(Received via mailing list)
Generalizing Daniel's solution:

543> cat tClassByName.rb
#!/bin/ruby -w

def class_by_name name
    name.split("::").inject(Object){ |c,n|
        c.const_get(n)
    }
end

p class_by_name( 'Hash' )
p class_by_name( 'File::Stat' )
__END__

544> ruby tClassByName.rb
Hash
File::Stat

regards
Sergey

----- Original Message -----
From: "Daniel Harple" <dharple@generalconsumption.org>
To: "ruby-talk ML" <ruby-talk@ruby-lang.org>
Sent: Tuesday, May 02, 2006 11:06 AM
Subject: Re: How to get a new instance of a class given a String
Bd6167863690cb320d65bb9204619817?d=identicon&s=25 David Clements (Guest)
on 2006-05-03 18:59
(Received via mailing list)
On 5/2/06, Sergey Volkov <gm.vlkv@gmail.com> wrote:
> end
> Sergey
Thanks so much that has me going again.

Dave

----- Original Message -----
This topic is locked and can not be replied to.