在 Ruby 中按名称以编程方式访问变量 [英] Access variables programmatically by name in Ruby

查看:45
本文介绍了在 Ruby 中按名称以编程方式访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不完全确定这在 Ruby 中是否可行,但希望有一种简单的方法可以做到这一点.我想声明一个变量,然后找出变量的名称.也就是说,对于这个简单的片段:

I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:

foo = ["goo", "baz"]

我怎样才能得到数组的名字(这里是foo")?如果确实有可能,这是否适用于任何变量(例如,标量、散列等)?

How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?

这就是我基本上要做的事情.我正在编写一个包含三个重要变量的类的 SOAP 服务器,验证代码本质上是这样的:

Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:

  [foo, goo, bar].each { |param|
      if param.class != Array
        puts "param_name wasn't an Array. It was a/an #{param.class}"
        return "Error: param_name wasn't an Array"
      end
      }

我的问题是:我可以用 foo、goo 或 bar 替换 'param_name' 的实例吗?这些对象都是数组,所以到目前为止我收到的答案似乎不起作用(除了重新设计整个事情ala dbr 的回答)

My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala dbr's answer)

推荐答案

如果您解决了问题怎么办?与其尝试从变量中获取名称,不如从名称中获取变量:

What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names:

["foo", "goo", "bar"].each { |param_name|
  param = eval(param_name)
  if param.class != Array
    puts "#{param_name} wasn't an Array. It was a/an #{param.class}"
    return "Error: #{param_name} wasn't an Array"
  end
  }

如果有可能根本没有定义变量(而不是不是数组),您可能希望在param = ..."行的末尾添加rescue nil"以防止 eval 抛出异常...

If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add "rescue nil" to the end of the "param = ..." line to keep the eval from throwing an exception...

这篇关于在 Ruby 中按名称以编程方式访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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