我在排序看起来像这样的哈希时遇到了麻烦:
{9=>["Blake Johnson", "Jack Bauer"],
7=>["Bart Simpson", "Homer Simpson"],
10=>["Avi Flombaum", "Jeff Baird"]}
我希望它看起来像这样:
{7=>["Blake Johnson", "Jack Bauer"],
9=>["Bart Simpson", "Homer Simpson"],
10=>["Avi Flombaum", "Jeff Baird"]}
答案 0 :(得分:5)
这个要求很奇怪,但这应该有效:
hash = {
9 => ["Blake Johnson", "Jack Bauer"],
7 => ["Bart Simpson", "Homer Simpson"],
10 => ["Avi Flombaum", "Jeff Baird"]
}
hash.keys.sort.zip(hash.values).to_h
#=> {7=>["Blake Johnson", "Jack Bauer"], 9=>["Bart Simpson", "Homer Simpson"], 10=>["Avi Flombaum", "Jeff Baird"]}
答案 1 :(得分:2)
hash = {
9 => ["Blake Johnson", "Jack Bauer"],
7 => ["Bart Simpson", "Homer Simpson"],
10 => ["Avi Flombaum", "Jeff Baird"]
}
Hash[hash.sort]
{ 7=>["Bart Simpson", "Homer Simpson"],
9=>["Blake Johnson", "Jack Bauer"],
10=>["Avi Flombaum", "Jeff Baird"]
}
答案 2 :(得分:0)
你可以这样做:
sorted_hash = {}
hash.sort.each do |key_value_pair|
key = key_value_pair[0]
value = key_value_pair[1]
sorted_hash[key] = value
end
sort方法返回一个排序的数组数组,其中这些内部数组的每个元素都是[key,{value}],它们按键排序(如果它是一个可排序的对象)。