如何在Ruby中将字符串转换为对变量的引用?

时间:2011-03-06 12:18:54

标签: ruby cucumber

我需要能够将变量的名称传递给表达式(在黄瓜中),并且希望能够将该字符串转换为引用(即不是副本)变量

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

由于Ruby是一种反思性语言,我确信我想要做的事情是可能的,但我还没有解决它。

3 个答案:

答案 0 :(得分:2)

  class Reference
    def initialize(var_name, vars)
      @getter = eval "lambda { #{var_name} }", vars
      @setter = eval "lambda { |v| #{var_name} = v }", vars
    end
    def value
      @getter.call
    end
    def value=(new_value)
      @setter.call(new_value)
    end
  end

来自http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc。祝你好运!

答案 1 :(得分:1)

解决方案可能是将事物包装到数组中。可以通过引用轻松传递。

irb(main):001:0> my_var = [10]
=> [10]
irb(main):002:0> my_var_copy = my_var
=> [10]
irb(main):003:0> my_var[0] = 55
=> 55
irb(main):004:0> my_var_copy
=> [55]

请参阅此处 - http://www.rubyfleebie.com/understanding-fixnums/

(稍微偏离主题,但给了我解决方案的初步想法) - http://ruby.about.com/od/advancedruby/a/deepcopy.htm

答案 2 :(得分:0)

可以obj.instance_variable_getobj.instance_variable_set为您提供帮助吗?