如何将字符串转换为Ruby中的变量的引用? [英] How do I convert a string into a reference to a variable in Ruby?

查看:584
本文介绍了如何将字符串转换为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.

例如

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.

推荐答案


  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 。祝你好运!

这篇关于如何将字符串转换为Ruby中的变量的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆