people = {:fred => 23,:joan => 18,:pete => 54
}
年龄排序:
people.values.sort # => [18, 23, 54]
姓名排序:
people.sort_by { |name, age| age }# => [[:joan, 18], [:fred, 23], [:pete, 54]]
或者
people.sort
一个复杂点的hash
people = {:fred => { :name => "Fred", :age => 23 },:joan => { :name => "Joan", :age => 18 },:pete => { :name => "Pete", :age => 54 }
}
people.sort_by { |k, v| v[:age] }# => [[:joan, {:name=>"Joan", :age=>18}], [:fred, {:name=>"Fred", :age=>23}],[:pete, {:name=>"Pete", :age=>54}]]