From: dblack@... Date: 2006-08-12T21:26:48+09:00 Subject: Re: newbie question: how to create variable Hi -- On Sat, 12 Aug 2006, Mr Pinto wrote: > On Aug 11, 2006, at 12:55 PM, Robert Klemme wrote: > >> Karel Michek wrote: >>> Hi, >>> how to create variable in the method that accepts string as name of the >>> variable and the object? Something like this: >>> class InterpreterCallback def set_object(name, value) >>> #do something here >> >> instance_variable_set("@#{name}", value) >>> end >>> end >>> $callback = InterpreterCallback.new() >>> $callback.set_object("var", 3) >>> puts var >>>>>> 3 > > Depending on what you're trying to do, you might be able to use a simple eval > statement: > irb(main):001:0> name="var" > => "var" > irb(main):002:0> value="3" > => "3" > irb(main):003:0> eval "#{name} = value" > => "3" > irb(main):004:0> var > => "3" That only works in irb. With ruby you'll get: ruby -e 'name="var"; value="3"; eval("#{name}=#{value}"); var' -e:1: undefined local variable or method `var' for main:Object (NameError) David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy ----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <----- http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log http://www.manning.com/black => book, Ruby for Rails http://www.rubycentral.org => Ruby Central, Inc.