From: "Peña, Botp" Date: 2007-06-18T11:59:41+09:00 Subject: sorting hash keys and values (was RE: Adding new value (in array) to existing key in a hash) On Behalf Of Gilbert Lau: # myhash = {"a" => [[0,0],[3,4]], "b" => [[1,1],[9,8]], "c" => [[7,6]]} # # how do I sort the values to become # # [0,0],[1,1],[3,4],[7,6],[9,8] # # and be able to recall the keys to arrange according to the sorted # values, like # # "a", "b", "a", "c", "b" just be careful w some value clashes irb(main):112:0> newhash={} => {} irb(main):113:0> myhash.each{|k,v| v.each{|e| newhash[e]=k}} => {"a"=>[[0, 0], [3, 4]], "b"=>[[1, 1], [9, 8]], "c"=>[[7, 6]]} # we create a new hash whose values are now keys # (like invert but your case is special) # so now values still point to their original keys irb(main):114:0> newhash => {[0, 0]=>"a", [1, 1]=>"b", [3, 4]=>"a", [7, 6]=>"c", [9, 8]=>"b"} irb(main):118:0> newhash.keys => [[0, 0], [1, 1], [3, 4], [7, 6], [9, 8]] irb(main):119:0> newhash.values => ["a", "b", "a", "c", "b"] irb(main):120:0> there is too much magic in there, i'm not sure how/why ruby sorted it (but i love it :) anyway, just to be sure irb(main):145:0> newhash.sort_by{|k,v| k} => [[[0, 0], "a"], [[1, 1], "b"], [[3, 4], "a"], [[7, 6], "c"], [[9, 8], "b"]] irb(main):146:0> newhash.sort_by{|k,v| k}.map{|e| e[0]} => [[0, 0], [1, 1], [3, 4], [7, 6], [9, 8]] irb(main):147:0> newhash.sort_by{|k,v| k}.map{|e| e[1]} => ["a", "b", "a", "c", "b"] kind regards -botp