tags:

views:

122

answers:

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
+7  A: 

You can achieve something similar using eval

x = "myvar"
myvar = "hi"
eval(x) -> "hi"
Anthony Forloney
+4  A: 

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
Is there an extra colon in there on line 3?
btelles
Yes, the colon is equivalent to calling to_sym on a string literal: convert it to a symbol.
molf
IOW `:"abcdef" == "abcdef".to_sym == :abcdef`, and you can use interpolation too `:"#{klazz}_#{id}" == "#{klazz}_#{id}".to_sym`.
Justice