courtesy of irb:
2.0.0-p0 :006 > @instance_variable = \"from an instance variable\"
=> \"from an instance variable\"
2.0.0-p0 :007 > variable = \"
In Ruby 2.1 and later, you can use Binding#local_variable_get.
In prior versions of Ruby, you have to use eval
. If you want to do some sanity-checking before evaluating a supposed variable name, you can check whether the named variable is in local_variables
.
You could use eval
:
irb(main):007:0> variable = "from a variable"
=> "from a variable"
irb(main):008:0> eval 'variable'
=> "from a variable"