From: Nico Ritsche Date: 2008-01-29T07:02:06+09:00 Subject: Re: Hash Sorting Nico Ritsche wrote: > Siep Korteling wrote: >> Ilan Berci wrote: >> >>> >>> ilan >> >> irb(main):001:0> h = {1=>2,3=>4,5=>6} >> => {5=>6, 1=>2, 3=>4} >> irb(main):002:0> h.to_a.sort >> => [[1, 2], [3, 4], [5, 6]] >> irb(main):003:0> h.to_a.sort_by {|a,b| b} >> => [[1, 2], [3, 4], [5, 6]] >> irb(main):004:0> >> >> h.to_a.sort_by {|a,b| b} #sorts by value; the OP wants to sort by key. >> h.to_a.sort_by {|key,value| key} >> #or just >> h.to_a.sort_by {|key|key} >> >> Regards, >> >> Siep > > > array.sort sorts by key, I know that. That's what I'm trying to do, but > it doesnt work in my case for some reason maybe this excerpt of my code helps to clarify what I'm trying to do (for those who know rails): @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 and the i like to iterate over the elements of the sorted array, so the result should look like this: pi_array_sorted = { 'general_event_types', [GeneralEventType1, GeneralEventType2, ..], 'prices', [Price1, Price2, ..], 'specific_event_types', [SpecificEventType1, SpecificEventType2, ..], 'general_event_types', [Teacher1, Teacher2, ..] } So the keys should be in alphabetical order, but they arent, at least not when I iterate over the array using pi_array_sorted.each do |a| .. end -- Posted via http://www.ruby-forum.com/.