如何将 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 是一种反射性语言,我确信我想做的事情是可能的,但我还没有破解它。
I need to be able to pass the name of a variable into an expression (in cucumber) and would like to be able to convert that string into a reference (i.e. not a copy) of the variable.
e.g.
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
Since Ruby is such a reflective language I'm sure what I'm trying to do is possible but I haven't yet cracked it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案可能是将事物包装到数组中。这可以很容易地通过引用传递。
请参阅此处 - http://www.rubyfleebie.com/understanding-fixnums/
并且(稍微偏离主题,但给了我解决方案的初步想法)在这里 - http:// ruby.about.com/od/advancedruby/a/deepcopy.htm
A solution might be to wrap things into an array. Which can easily be passed around by reference.
See here - http://www.rubyfleebie.com/understanding-fixnums/
And (slightly off topic, but gave me the initial idea for a solution) here - http://ruby.about.com/od/advancedruby/a/deepcopy.htm
可以 obj.instance_variable_get 和 obj.instance_variable_set 对您有帮助吗?
Could obj.instance_variable_get and obj.instance_variable_set help you?
从 http://onestepback.org/index.cgi/Tech/Ruby/ 得到这个RubyBindings.rdoc。祝你好运!
Got this from http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc. Good luck!