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
  • 160,959
  • 41
  • 265
  • 366
Lasse Sviland
  • 1,458
  • 10
  • 23

3 Answers3

35
binding.local_variable_get("variable")
# => 22
sawa
  • 160,959
  • 41
  • 265
  • 366
6

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
  • 15,367
  • 3
  • 51
  • 68
  • 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,018
  • 2
  • 27
  • 37
  • 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