Forum: Ruby Create named objects

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Roland S. (Guest)
on 2006-03-01 17:36
(Received via mailing list)
Hello,

want to do the following:

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

<<<some magic here>>>

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


Thanks in advance,

Roland
unknown (Guest)
on 2006-03-01 18:33
(Received via mailing list)
Roland S. 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
string

# in your insert magic here:
evs = "#{name} = #{clazz}.new( #{value} )"
eval( evs )
unknown (Guest)
on 2006-03-01 18:42
(Received via mailing list)
Hi --

On Thu, 2 Mar 2006, removed_email_address@domain.invalid 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

--
David A. Black (removed_email_address@domain.invalid)
Ruby Power and Light (http://www.rubypowerandlight.com)

"Ruby for Rails" chapters now available
from Manning Early Access Program! http://www.manning.com/books/black
Logan C. (Guest)
on 2006-03-01 21:12
(Received via mailing list)
On Mar 1, 2006, at 11:33 AM, removed_email_address@domain.invalid wrote:

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

alternatively:

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

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

puts(input)
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.