From: Nico Ritsche Date: 2008-01-30T15:39:27+09:00 Subject: Re: Hash Sorting Ilan Berci wrote: > Nico Ritsche wrote: >> Rodrigo Kochenburger wrote: >>>> pi_array_sorted = >>>> { 'general_event_types', �[GeneralEventType1, GeneralEventType2, ..], >>>> � 'prices', � � � � � � � [Price1, Price2, ..], >>>> � 'specific_event_types', [SpecificEventType1, SpecificEventType2, ..], >>>> � 'general_event_types', �[Teacher1, Teacher2, ..] } >>>> > >> Nico > > Nico, > > We can help but you must strive to explain what you want clearly and > legibly.. For the pi_array_sorted, it appears that you want to convert a > hash of arrays into an array of arrays where the second arrays is > sorted. > > Here is a solution that sorts the nested arrays and then the initial > array > > irb(main):002:0> a = {1=>[3,7,1,7], 2=>[3,7,1,1],3=>[3,2,2,9]} > => {1=>[3, 7, 1, 7], 2=>[3, 7, 1, 1], 3=>[3, 2, 2, 9]} > irb(main):003:0> a.each {|b,c| c.sort!} > => {1=>[1, 3, 7, 7], 2=>[1, 1, 3, 7], 3=>[2, 2, 3, 9]} > irb(main):004:0> a.sort > => [[1, [1, 3, 7, 7]], [2, [1, 1, 3, 7]], [3, [2, 2, 3, 9]]] > > hth > > If it doesn't then write the code EXACTLY as you have it.. and then the > exact output that you desire and we will code it for you.. The code that > you submitted is barely readable and leaves a lot open to > interpretation. > > ilan Hi Ilan, actually I supplied my exact code already. So here again, my exact code that doesn't work: @parent_items = {} @parent_items['teachers'] = Teacher.find(:all) @parent_items['prices'] = Price.find(:all) @parent_items['general_event_types'] = GeneralEventType.find(:all, :conditions => "language_parent_id = id") @parent_items['specific_event_types'] = SpecificEventType.find(:all, :conditions => "language_parent_id = id") pi_array_sorted = @parent_items.to_a.sort So what I'm doing here is building a hash containing arrays of rails active record objects. So for example @parent_items['teachers'] is an array of Teacher records. Then I call the hashs's sort method. After doing this I expect pi_array_sorted to be a nested array, sorted by key, as the documentation of Hash.sort suggests ("Converts hsh to a nested array of [ key, value ] arrays and sorts it, using Array#sort."). So the result for the above code should be this nested array: [ 'general_event_types', [GeneralEventType1, GeneralEventType2, ..], 'prices', [Price1, Price2, ..], 'specific_event_types', [SpecificEventType1, SpecificEventType2, ..], 'teachers', [Teacher1, Teacher2, ..] ] But this is not what I get. The keys in the resulting array still have an arbitrary order, the exact same order as if I don't call .sort at all. Nico -- Posted via http://www.ruby-forum.com/.