Access variables programmatically by name in Ruby -
i'm not entirely sure if possible in ruby, there's easy way this. want declare variable , later find out name of variable. is, simple snippet:
foo = ["goo", "baz"]
how can name of array (here, "foo") back? if indeed possible, work on variable (e.g., scalars, hashes, etc.)?
edit: here's i'm trying do. i'm writing soap server wraps around class 3 important variables, , validation code this:
[foo, goo, bar].each { |param| if param.class != array puts "param_name wasn't array. a/an #{param.class}" return "error: param_name wasn't array" end }
my question then: can replace instances of 'param_name' foo, goo, or bar? these objects arrays, answers i've received far don't seem work (with exception of re-engineering whole thing ala dbr's answer)
what if turn problem around? instead of trying names variables, variables names:
["foo", "goo", "bar"].each { |param_name| param = eval(param_name) if param.class != array puts "#{param_name} wasn't array. a/an #{param.class}" return "error: #{param_name} wasn't array" end }
if there chance of 1 variables not being defined @ (as opposed not being array), want add "rescue nil" end of "param = ..." line keep eval throwing exception...
Comments
Post a Comment