How to convert a string to a variable reference in Ruby?

I need to be able to pass the variable name into an expression (in a cucumber) and want to be able to convert this string to a link (i.e. not a copy) of the variable.

eg.

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 I'm trying to do it, but I haven't cracked it yet.

0
source share
3 answers
  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. !

+2

, . .

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

+1

All Articles