Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variables programmatically by name in Ruby

Tags:

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"] 

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

Edit: 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       } 

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)

like image 571
Chris Bunch Avatar asked Sep 12 '08 08:09

Chris Bunch


1 Answers

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

like image 79
glenn mcdonald Avatar answered Sep 28 '22 22:09

glenn mcdonald