13

I have a local variable name as a string, and need to get its value.

variable = 22
"variable".to_variable?

How can I get the value 22 form the string?

sawa
  • 165,429
  • 45
  • 277
  • 381
Lasse Sviland
  • 1,479
  • 11
  • 23

3 Answers3

40
binding.local_variable_get("variable")
# => 22
sawa
  • 165,429
  • 45
  • 277
  • 381
5

You can use eval.

variable = 22
eval("variable")
# => 22 

However eval can be nasty. If you dont mind declaring an instance variable, you can do something like this too:

@variable = 22
str = "variable"
instance_variable_get("@#{str}")
# => 22
Community
  • 1
  • 1
shivam
  • 16,048
  • 3
  • 56
  • 71
  • 10
    There is no need for `eval` here, just use [`Binding#local_variable_get`](http://ruby-doc.org/core-2.2.2/Binding.html#method-i-local_variable_get). – Jörg W Mittag Jun 15 '15 at 11:07
  • 1
    @JörgWMittag I learned about binding just today through [sawa's answer](http://stackoverflow.com/a/30840502/3035830). I knew eval was bad so mentioned that in my answer. But thanks for pointing out.. :) – shivam Jun 15 '15 at 11:11
1

use eval() method:

variable = 22
eval "variable" #"variable".to_variable?
# => 22
usmanali
  • 2,028
  • 2
  • 27
  • 38
  • 5
    There is no need for `eval` here, just use [`Binding#local_variable_get`](http://ruby-doc.org/core-2.2.2/Binding.html#method-i-local_variable_get). – Jörg W Mittag Jun 15 '15 at 11:07