[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Ruby hashes

Alvaro Perez

11/22/2007 3:54:00 PM

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?
--
Posted via http://www.ruby-....

3 Answers

Alex Young

11/22/2007 4:02:00 PM

0

Alvaro Perez wrote:
> 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}

--
Alex

Sebastian Hungerecker

11/22/2007 4:04:00 PM

0

Alvaro Perez wrote:
> 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
--
NP: Explosions in the Sky - Snow And Lights
Jabber: sepp2k@jabber.org
ICQ: 205544826

Alvaro Perez

11/22/2007 4:13:00 PM

0

Wow, exactly same solution ;)

but it works! thank you very much to both.
--
Posted via http://www.ruby-....