在Ruby哈希中对键进行排序,而不更改其原始位置的关联值

时间:2015-02-12 15:20:06

标签: ruby sorting

我在排序看起来像这样的哈希时遇到了麻烦:

{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"]}

3 个答案:

答案 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}],它们按键排序(如果它是一个可排序的对象)。