ruby - 如何根据一些自定义规则对 ruby​​ 中的哈希进行排序

标签 ruby hash

<分区>

我有一个这样的数组:

["Is", "Gandalf", "The", "Gray", "Insane"]

我想根据键在数组中的位置对散列进行排序。例如,我想排序:

{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5}

进入这个:

{"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21}

另一个例子是排序:

{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2}

进入这个:

{"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3}

如何做到这一点?

最佳答案

class Hash
  def sort_by_array a; Hash[sort_by{|k, _| a.index(k) || length}] end
end

将适用于第一个示例:

a = ["Is", "Gandalf", "The", "Gray", "Insane"]

{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5}.sort_by_array(a)
# => {"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21}

但是,它不适用于您的第二个示例,因为您期望的第二个示例的结果不仅仅是排序,而且还需要更改 "Gray" 的值:

{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2}.sort_by_array(a)
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>0, "Insane"=>22, :count=>3}

# You wanted
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3}

由于不清楚 "Gray" 的值 12 从何而来,因此无法以满足第二个示例的方式回答您的问题。

关于ruby - 如何根据一些自定义规则对 ruby​​ 中的哈希进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14140419/

相关文章:

postgresql - 表达式中带有 sha() 函数的 Postgres 索引

ruby - 在 Windows 上的 Ruby 1.9.1 上安装 Hpricot

mysql - 在 ruby​​ on Rails 中追加查询

ruby - 使用正则表达式获取 URL 的域

ruby 心印 : regex parentheses "capture" matched content?

ruby - 如何使用新的 ruby​​ (1.9) 哈希语法从关联创建符号(哈希键)?

ruby - 在获取嵌套的 ruby​​ 哈希层次结构方面需要帮助

java - 我如何从对象中获取哈希值/md5?

hash - 我什么时候不使用 HashMap ?

Ruby:比较两个哈希数组