开发者

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

开发者 https://www.devze.com 2022-12-18 08:59 出处:网络
This question already has answers here: How to dynamically create a local variable? (4 answers) Closed 3 years ago.
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

精彩评论

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