From: Florian Gross Date: 2004-12-14T06:07:19+09:00 Subject: Re: [Nuby] Sorting a Hash and keepint it as a Hash? Williams, Chris wrote: > I have a Hash of objects which I want to sort by the values. Afterwards > I want to pull out the keys as one array and the values as another. So I > have code like so: > > # sort by frequency ascending > @fault_sums = @fault_sums.sort {|a,b| a[1] <=> b[1]} > # Only keep top N > @fault_sums.slice!(0...-@number) if @number <= @fault_sums.size > > fields = @fault_sums.keys > data = @fault_sums.values > > But when I get to calling keys and values on the Hash I realized, sort > actually returns back a 2D array and those methods aren't defined on an > Array. Is there a way to make the 2D Array returned by the sort back > into a Hash? There's no sorted Hashs in Standard Ruby so you will get a sorted Array of pairs. However you can use a nifty trick to get the keys and values out of that: [['key1', 'value1'], ['key2', 'value2']].transpose # => [['key1', 'key2'], ['value1', 'value2']] So this will solve your problem: top_pairs = @faults_sum.sort_by { |key, value| -value }.first(@number) fields, data = *top_pairs.transpose Note that I chose to sort descending and to keep the first (high sum) entries instead of sorting ascending and to keep the lowest (high sum) entries in reverse.