开发者

Is it possible to do dynamic variables in ruby? [duplicate]

This question already has answers here: How to dynamically create a local variable? (4 answers) Closed 3 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜