是否有“variable_get"方法?如果没有,我如何创建自己的? [英] Is there a 'variable_get' method? If not, how can I create my own?

查看:26
本文介绍了是否有“variable_get"方法?如果没有,我如何创建自己的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由 irb 提供:

2.0.0-p0 :006 > @instance_variable = "from an instance variable"
 => "from an instance variable" 
2.0.0-p0 :007 > variable = "from a variable"
 => "from a variable" 
2.0.0-p0 :008 > instance_variable_get(:@instance_variable)
 => "from an instance variable" 
2.0.0-p0 :009 > variable_get(:variable)
NoMethodError: undefined method `variable_get' for main:Object
    from (irb):9
    from /usr/local/rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'
2.0.0-p0 :010 > 

我只是想以编程方式查询"一个变量并返回其内容.与 instance_variable_get 完全一样,但用于变量.

I'm simply trying to programmatically 'query' for a variable and return its contents. Exactly like instance_variable_get but for a variable.

它用于自定义 rspec 匹配器.不是一些疯狂的解决方法:)

It's for a custom rspec matcher. Not some crazy workaround :)

推荐答案

在 Ruby 2.1 及更高版本中,您可以使用 绑定#local_variable_get.

In Ruby 2.1 and later, you can use Binding#local_variable_get.

在以前的 Ruby 版本中,您必须使用 eval.如果您想在评估假定的变量名称之前进行一些完整性检查,您可以检查命名变量是否在 local_variables 中.

In prior versions of Ruby, you have to use eval. If you want to do some sanity-checking before evaluating a supposed variable name, you can check whether the named variable is in local_variables.

这篇关于是否有“variable_get"方法?如果没有,我如何创建自己的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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