Dynamically Naming a Variable

Hello,
I would like to dynamically name a variable… for example, in my
program, I iterate over a SQL query that gives me ‘displayname’,
‘phone_office’, and ‘phone_mobile’ (in the actual query there are many
more columns). For each row in the results, I want to create an array
with [0]=‘phone_office’ and [1]=‘phone_mobile’ and then I would like to
name the array the ‘displayname’. Is there a way I could do this?

Any help is appreciated!

Thanks!

  • Jeff M.

I can’t believe i’m about to post this, but this will work

user = User.find(params[:id])
arr = eval(“#{@user.user_name} = []”)
User.column_names.each { |name| arr[arr.size] = user[name.to_sym] }

On Apr 24, 3:15 pm, Jeff M. [email protected]

Honestly though I’d urge you to use a hash:

directory = {}
directory[display_name] = []
results = your_SQL_query
results.each {|r| directory[display_name].push r}

On Apr 24, 3:15 pm, Jeff M. [email protected]

thanks for your help, a co-worker of mine just showed me how to use
hashes. I’m still pretty new to Ruby, so I honestly didn’t even know of
how powerful a hash can be. It makes a lot more sense to do it that way!

Thanks again,

  • Jeff M.