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
···
On Oct 3, 2005, at 11:45 PM, Hal Fulton wrote:
Felix McCoey wrote:
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
On 10/3/05, Hal Fulton <hal9000@hypermetrics.com> wrote:
Felix McCoey wrote:
> 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
>
On 10/3/05, Hal Fulton <hal9000@hypermetrics.com> wrote:
Felix McCoey wrote:
> 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
>