Access variables programmatically by name in Ruby

后端 未结 11 895
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 19:15

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.

11条回答
  •  一向
    一向 (楼主)
    2020-11-27 19:35

    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
      }
    

    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...

提交回复
热议问题