Access variables programmatically by name in Ruby

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…

Leave a Comment