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"
···
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
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)
------------ Původní zpráva ------------
Od: <dblack@wobblini.net>
Předmět: Re: newbie question: how to create variable
Datum: 12.8.2006 14:27:31
----------------------------------------
Hi --
>
>> 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
ruby -e 'name="var"; value="3"; eval("#{name}=#{value}"); var'
-e:1: undefined local variable or method `var' for main:Object
(NameError)
David
None of this actually works quite well for me. I am using SWIG directors to embed ruby (and python, perl) into C# application trough C++ layer. value actually wraps C++ object . InterpreterCallback actually extends c++ class and I am calling set_object() from C++ - set_object("editor", getEditor() ) - "editor" then can be used in the global namespace for scripting convenience: