Reputation: 15374
I need to convert a string "variable_1"
into the value that the global variable $variable_1
holds. The value of $variable_1
will have already been defined. How can I convert a string into an object? Is this possible?
I looked at the method instance_variable_set
but this does not suit my needs.
A thread on rubyforums advises that eval
could be used, for example if I was to compare two variables using cucucmber and rspec, I could do something like:
Then(/^I expect my variables to be different "(.*?)" "(.*?)"$/) do |count1, count2|
expect(eval("$#{count1}")).not_to eq(eval("$#{count2}"))
end
Is there another way to obtain a global variable from a string of its name?
Upvotes: 1
Views: 808
Reputation: 2869
You can use eval
method like this
$variable_1 = "Try"
s = "variable_1"
eval("$#{s}")
puts $variable_1
# => Try
Upvotes: 2