Combining two arrays

Hi,

I have two arrays: one that contains ids and data values and one that
contains ids and names. There is a relationship between the ids in the
two arrays. How do I create a third array that contains names and data
values? This is basically a lookup to replace ids pulled from a
database with a readable name.

Thanks,

David

I assume you mean’t Hashes and not Arrays?

This assumes the elements are in the same order:

names = {:one => “one”, :two => “two”}
data = {“one” => “foo”, “two” => “bar”}
hash = {}
names.values.zip(data.values).each {|key, value| hash[key] = value}
hash
=> {“two”=>“bar”, “one”=>“foo”}

I’m using find to return to sets of data from a database that need to be
combined to display in an html table. The id is in one array, but the
corresponding name I need to display is in the other array because it’s
in another table. How do I combine them so I can display the name in
the table instead of the id?

Or is it better to do a join using rails so I only return a single set
of data from the database?

Thanks,

David

I’d go with a JOIN, it’s no doubt faster.

Array#zip

Or, a join.

On 9/22/06, David L. [email protected] wrote:

Thanks,

David


Posted via http://www.ruby-forum.com/.


When a man says he approves of something in principle, it means he
hasn’t the slightest intention of putting it into practice. –
Bismarck

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs