按其值对哈希进行排序

时间:2019-07-14 17:25:35

标签: ruby sorting

我需要按其值对散列进行排序(我希望具有相同的散列;但是具有相同值的键彼此相邻)。

{"ThErBro"=>"BEhorrT", "Jean"=>"aeJn", "Brother"=>"Behorrt", 
"eanJ"=>"aeJn"}

我不知道如何按键值对键进行排序并保留哈希值! (没有数组作为输出...)。

然后我想创建一个数组;在这里,我将具有相同值的键分组到一个嵌套数组中。然后删除每个值,以仅保留以前具有相同值的键。 (这也是我也不知道该怎么做的地方...) 这是我想要的输出:

[["ThErBro", "Brother"], ["Jean", "eanJ"]]

我对这个红宝石世界很了解,任何解释将不胜感激。 谢谢

1 个答案:

答案 0 :(得分:2)

h = {"Jean"=>"aeJn", "ThErBro"=>"BEhorrT", "eanJ"=>"aeJn", "Brother"=>"BEhorrT"}

h.each_with_object(Hash.new { |h,k| h[k] = [] }) { |(k,v),g| g[v] << k }.
  sort_by(&:first).
  map(&:last)
    #=> [["ThErBro", "Brother"], ["Jean", "eanJ"]] 

步骤如下。

g = h.each_with_object(Hash.new { |h,k| h[k] = [] }) { |(k,v),g| g[v] << k }
  #=> {"aeJn"=>["Jean", "eanJ"], "BEhorrT"=>["ThErBro", "Brother"]} 
a = g.sort_by(&:first)
  #=> [["BEhorrT", ["ThErBro", "Brother"]], ["aeJn", ["Jean", "eanJ"]]] 
a.map(&:last)
  #=> [["ThErBro", "Brother"], ["Jean", "eanJ"]] 

哈希

h = Hash.new { |h,k| h[k] = [] }

具有以下属性:如果h没有键k,则h[k]返回一个空数组。等效于:

h = {}
pr = proc { |h,k| [] } 
h.default_proc = pr

请参见Hash::newHash#default_proc=

以这种方式定义h并且h没有密钥k时,

h['cat'] << 'meow'
  #=> ["meow"] 
h['cat'] << 'meow, meow'
  #=> ["meow", "meow, meow"] 

在第一条语句中,h['cat']设置为一个空数组(因为h没有键'cat'),然后将'meow'附加到该数组。在第二个语句h中有一个键'cat',因此'meow, meow'只是附加到数组中。等效于:

h = {}
h['cat'] = [] unless g.key?('cat')
h['cat'] << 'meow'
  #=> ["meow"] 
h['cat'] << 'meow, meow'
  #=> ["meow", "meow, meow"]