Forum: Ruby Create named objects

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
5c6dae370b5f447866747b5c6691608e?d=identicon&s=25 Roland Schmitt (Guest)
on 2006-03-01 16:36
(Received via mailing list)

want to do the following:

name = "input"
clazz = "String"
value = "test"

<<<some magic here>>>

puts(input) -> "test"
input.class() -> String

Thanks in advance,

4a4f9063a3088bafbea80d18c40818e6?d=identicon&s=25 unknown (Guest)
on 2006-03-01 17:33
(Received via mailing list)
Roland Schmitt wrote:
> puts(input) -> "test"
> input.class() -> String
> Thanks in advance,
> Roland

a pretty straight forward way is to just use the eval function on a

# in your insert magic here:
evs = "#{name} = #{clazz}.new( #{value} )"
eval( evs )
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-03-01 17:42
(Received via mailing list)
Hi --

On Thu, 2 Mar 2006, wrote:

>> <<<some magic here>>>
> string
> # in your insert magic here:
> evs = "#{name} = #{clazz}.new( #{value} )"
> eval( evs )

That will create a new inner scope, so if there's no variable named
input already, there won't be one when the eval exits.  (Which is
good, because otherwise we'd probably be seeing a lot of this kind of
thing :-)

The best advice, though it's not exactly an answer to the question,
is: use a hash.

   name = "input"
   value = "test"
   value_hash[name] = test

rather than the "soft reference"-style (to borrow a Perl phrase) way
of creating locals.


David A. Black (
Ruby Power and Light (

"Ruby for Rails" chapters now available
from Manning Early Access Program!
E34b5cae57e0dd170114dba444e37852?d=identicon&s=25 Logan Capaldo (Guest)
on 2006-03-01 20:12
(Received via mailing list)
On Mar 1, 2006, at 11:33 AM, wrote:

>> <<<some magic here>>>
> string
> # in your insert magic here:
> evs = "#{name} = #{clazz}.new( #{value} )"
> eval( evs )


name =  "input"
clazz = "String"
value = "test"

(class << self; self; end).class_eval { define_method(name)
{ const_get(clazz).new(value) } }

puts input.class

There are several disadvantages to this approach.
1) input is a method not  really a variable and therefore its scope
is gonna be all sorts of wrong
2) Since it is a method, assigning to it is not necessarily going to
work the way you want

Advantages ares that yo don't have to worry about the having seen an
assignment to it business and you don't have to invoke the parser

Yet another method would be
instance_variable_set("@#{name}", Object.const_get(clazz).new(value))

Unfortunately now you have to refer to it  as @input. It also has
some scoping issues.
This topic is locked and can not be replied to.