[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Create named objects

Roland Schmitt

3/1/2006 3:36:00 PM

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


3 Answers

kgoblin

3/1/2006 4:31:00 PM

0


Roland Schmitt wrote:
> 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

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 )

dblack

3/1/2006 4:42:00 PM

0

Logan Capaldo

3/1/2006 7:12:00 PM

0


On Mar 1, 2006, at 11:33 AM, kgoblin@gmail.com wrote:

>
> Roland Schmitt wrote:
>> 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
>
> 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 )

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.