Is it possible to do dynamic variables in ruby? [duplicate]
I can accomplish this dynamic nature in other 开发者_StackOverflow中文版ways, but it caused me to be curious. Is there a similar mechanism to this in Ruby?
$varname = "hello";
$$varname = "world";
echo $hello; //Output: world
You can achieve something similar using eval
x = "myvar"
myvar = "hi"
eval(x) -> "hi"
It's possible only for instance variables (and class variables):
class MyClass
def initialize
@varname = :"@hello"
instance_variable_set @varname, "world"
end
def greet
puts instance_variable_get(@varname)
end
end
MyClass.new.greet
#=> "world"
For local variables you have to use eval
.
精彩评论