From: Logan Capaldo Date: 2004-12-14T05:19:57+09:00 Subject: Re: [Nuby] Sorting a Hash and keepint it as a Hash? On Tue, 14 Dec 2004 05:07:03 +0900, Williams, Chris wrote: > Another nuby question: > > 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? > > Thanks, > Chris Williams > > Well you could but you'd be back at square one since a hash is unordered. An alternate method is to sort the keys by the values, ie keys_ordered = some_hash.keys.sort { |a, b| some_hash[a] <=> some_hash[b] } keys_ordered.each { |k| # do something with some_hash[k] } Of course you'll have to change it to fit exactly what you need.