All class and module objects are stored as constants in Object. It
gets a little tricky if you have a class withing a module --
"Music::Song". Then you'll have to do something like this:
current = Object
var2 = "Music::Song"
var2.split("::").each do |str|
current = current.const_get(str)
end
var1 = current.new( ... )
Hope this helps
TwP
···
On 2/14/07, Luca Scaljery <lcalje@gmail.com> wrote:
Hi All
I have a situation in which I have the name of the class in a variable
So normally I would do
song = Song.new("Bicylops", "Fleck", 260)
But I need to do something like
var2 = "Song"
var1 = var2.new("Bicylops", "Fleck", 260)
This doesn't work!
Any suggestions how to do this ?
I have a situation in which I have the name of the class in a variable
So normally I would do
song = Song.new("Bicylops", "Fleck", 260)
I'm surprised no one else has mentioned this, but there's very little need to
store a class name in a string. Usually if you're doing this then there's
something wrong with your methodology and there's a much more efficient way to
get the right results.
The only real reason I can think that you'd have that in a string and not simple
as the class constant is if you took it from user input. Hopefully you aren't
letting your users decide which classes get instantiated..!