2

I can accomplish this dynamic nature in other 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
g00se0ne
  • 4,560
  • 2
  • 21
  • 14

2 Answers2

7

You can achieve something similar using eval

x = "myvar"
myvar = "hi"
eval(x) -> "hi"
Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
5

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.

molf
  • 73,644
  • 13
  • 135
  • 118