From: Riccardo Cecolin Date: 2010-03-23T03:33:51+09:00 Subject: Re: Sorting keys of hash based on value Aldric Giacomoni wrote: > Let's say we have this contrived example: > > hash = {:a => {:happy => 5}, > :b => {:happy => 4}, > :c => {:happy => 7} > } > > I would like to get the keys sorted by descending :happy value, like so: > > [:c, :a, :b] > > How would I do this? > The best I've come up with is this: > > irb(main):018:0> hash.sort_by { |x, y| -y[:happy] } > => [[:c, {:happy=>7}], [:a, {:happy=>5}], [:b, {:happy=>4}]] > > It's not elegant :( > Do you want keys or the whole hash? irb(main):015:0> hash.keys.sort { |a,b| hash[b][:happy] <=> hash[a][:happy] } => [:c, :a, :b]