creating objects

F

Felix McCoey

i know that in PHP it is possible to do the following:

$class_name = 'User';
$$class_name->new()

but I want to do this in ruby like this perhaps:

@class_name = 'User'
@class_name.new

What is this called and is it possible in ruby. Or is there an
alternative to creating objects from just the class name?

-felix
 
H

Hal Fulton

Felix said:
i know that in PHP it is possible to do the following:

$class_name = 'User';
$$class_name->new()

but I want to do this in ruby like this perhaps:

@class_name = 'User'
@class_name.new

What is this called and is it possible in ruby. Or is there an
alternative to creating objects from just the class name?

You can always use const_get:

class_name = 'User'
klass = Object.const_get(class_name)
obj = klass.new


Hope this helps...


Hal
 
J

Joshua Haberman

--Apple-Mail-10--222254668
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=US-ASCII;
delsp=yes;
format=flowed


You can always use const_get:

class_name = 'User'
klass = Object.const_get(class_name)
obj = klass.new

Also, if you can create a string of code that does what you want, you
can always eval() it:

obj = eval("#{class_name}.new")

But the const_get solution is better. It works because classes are
live objects that are stored in global constants.

Josh

--Apple-Mail-10--222254668--
 
A

Adam Shelly

@class_name =3D User
@class_name.new

-or-

@class_name =3D "User"
eval @class_name+".new"
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top