ハッシュをソートする

キーでソートする

h = Hash[*%w[Apple red Banana yellow Lemon yellow Carrot orange Grape purple]]
a = h.keys.sort # キーを配列にしてソートする
p a #=> ["Apple", "Banana", "Carrot", "Grape", "Lemon"]

a.each{|x| p "#{x} is #{h[x]}"}
#=> "Apple is red"
#=> "Banana is yellow"
#=> "Carrot is orange"
#=> "Grape is purple"
#=> "Lemon is yellow"


一度[key,value]の配列にしてからソートする

h = Hash[*%w[Apple red Banana yellow Lemon yellow Carrot orange Grape purple]]
a = h.to_a # 配列にする
p a.sort_by {|x| [x[1],x[0]] }
# または p a.sort_by {|x,y| [y,x] }
#=> [["Carrot", "orange"], ["Grape", "purple"], ["Apple", "red"], ["Banana", "yellow"], ["Lemon", "yellow"]]

値でソートする.同値の場合はキーでソート.

配列のソートについては配列をソート - ロバの耳を参照.