我需要能够将变量的名称传递给表达式(在黄瓜中),并且希望能够将该字符串转换为变量的引用(即不是副本)。如何将字符串转换为对Ruby中变量的引用?
例如
Given /^I have set an initial value to @my_var$/ do
@my_var = 10
end
# and now I want to change the value of that variable in a different step
Then /^I update "([^"]*)"$/ do |var_name_string|
# I know I can get the value of @my_var by doing:
eval "@my_var_copy = @#{var_name_string}"
# But then once I update @my_var_copy I have to finish by updating the original
eval "@#{var_name_string} = @my_var_copy"
# How do instead I create a reference to the @my_var object?
end
由于Ruby是这样一种反射语言,我相信我想要做的事情是可能的,但我还没有破解它。
非常好 - 这是我所知道的,谢谢。它仍然不是100%,因为我需要使用ref_name.value,但它比我所得到的要好。 – 2011-03-08 17:15:46
我上面提供的链接具有ref_name.value的示例用法。它应该可能有你所需要的。 – RubyFanatic 2011-03-08 18:37:46