Ruby hashes

A

Alvaro Perez

Is there a way in Ruby to pass a hash value from string (or whatever) to
an Array dinamically?

Example: An array of objects Teacher, each with his name and belonging
school. After iterating though its elements, we want an output of the
type, "school_name_A" => "teacher_name_A", "school_name_B" =>
["teacher_name_B", "teacher_name_C"].

...or maybe there is another simpler way of doing this?
 
A

Alex Young

Alvaro said:
Is there a way in Ruby to pass a hash value from string (or whatever) to
an Array dinamically?

Example: An array of objects Teacher, each with his name and belonging
school. After iterating though its elements, we want an output of the
type, "school_name_A" => "teacher_name_A", "school_name_B" =>
["teacher_name_B", "teacher_name_C"].
It's easier if you allow:

{"school_name_A" => ["teacher_name_A"],
"school_name_B" => ["teacher_name_B", "teacher_name_C"]}

That way you can do this:

schools = Hash.new{|h,k| h[k] = []}
teachers.each {|teacher| schools[teacher.school] << teacher.name}
 
S

Sebastian Hungerecker

Alvaro said:
Example: An array of objects Teacher, each with his name and belonging
school. After iterating though its elements, we want an output of the
type, "school_name_A" => "teacher_name_A", "school_name_B" =>
["teacher_name_B", "teacher_name_C"].

hash = Hash.new {|h,k| h[k] = []}
teachers.each do |teacher|
hash[teacher.school] << teacher.name
end


HTH,
Sebastian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Iterating over an Array of Hashes 14
process multiple hashes 5
Hashes 6
2d array of hashes 3
Hashes 4
Iterating hashes 11
Array of Hashes in an array of hashes - Complicated! 16
Array of hashes issue 6

Members online

Forum statistics

Threads
474,270
Messages
2,571,353
Members
48,038
Latest member
HunterDela

Latest Threads

Top