Hello,
want to do the following:
name = “input”
clazz = “String”
value = “test”
<<>>
puts(input) -> “test”
input.class() -> String
Thanks in advance,
Roland
Hello,
want to do the following:
name = “input”
clazz = “String”
value = “test”
<<>>
puts(input) -> “test”
input.class() -> String
Thanks in advance,
Roland
Hi –
On Thu, 2 Mar 2006, [email protected] wrote:
<<>>
stringin 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 ([email protected])
Ruby Power and Light (http://www.rubypowerandlight.com)
“Ruby for Rails” chapters now available
from Manning Early Access Program! Ruby for Rails
Roland S. wrote:
puts(input) -> “test”
input.class() -> StringThanks in advance,
Roland
a pretty straight forward way is to just use the eval function on a
string
evs = “#{name} = #{clazz}.new( #{value} )”
eval( evs )
On Mar 1, 2006, at 11:33 AM, [email protected] wrote:
<<>>
stringin 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.
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs