how to do: var1 = var2.new(.....) (var2 contains classname)

L

Luca Scaljery

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 ?

Thnx
LuCa
 
L

Lyle Johnson

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 ?

var1 = Object.get_const(var2).new("Bicyclops", "Fleck", 260)
 
T

Tim Pease

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 ?

You need to convert your string "Song" into a Class object.

var2 = "Song"
var1 = Object.const_get(var2).new("Bicyclops", "Fleck", 260)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top