Hash:
Ruby的key-value数据结构就是Hash。如 myhash = {2 => 5, "he" => "ggg"};
经常要对hash排序,如
metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 } metrics.sort_by {|_key, value| value} # ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]
If you need a hash as a result, you can use to_h (in Ruby 2.0+) metrics.sort_by {|_key, value| value}.to_h # ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}
metrics.sort_by(&:last)
metrics.sort {|a1,a2| a2[1].to_i <=> a1[1].to_i }