【问题标题】:Sort ruby hash of array and hashes [closed]对数组和散列的红宝石散列进行排序[关闭]
【发布时间】:2019-11-03 13:35:51
【问题描述】:

是否有任何递归方式对由任何其他类型的可排序数据(通常是哈希和数组)组成的哈希进行排序?

我有

tagindex = Hash.new()
tagindex['keywords'] = Hash.new()
tagindex['authors'] = Hash.new()
tagindex['languages'] = Hash.new()
tagindex['licenses'] = Hash.new()

对于tagindex['keywords'] 中的每个keytagindex['keywords'][key] 是一个数组。

【问题讨论】:

  • 任何数据样本?
  • 您不能对哈希进行排序,因为它不是有序结构。
  • @Richard-Degenne 不正确,只是没有必要。 ruby Hashes 从 1.9.3 开始订购(基于密钥插入顺序),您可以使用 Enumerable#sortEnumerable#sort_by 对它们进行排序
  • @engineersmnky,您会承认 Ruby 中的许多东西是不必要的,但可能有用。我已经在 SO 上发布了几个答案,它们充分利用了哈希中的键顺序。像现在一样,我经常尝试找到一个,将其链接起来,但没有成功。我会收藏下一个。
  • @CarySwoveland 是的 "CarySwoveland" AND "order" AND "hash" AND "ruby" site:stackoverflow.com 返回“大约 364 个结果”

标签: arrays ruby sorting hash


【解决方案1】:
unordered_hash = {keywords: { a: 1, c: 2, b: 3}, authors: [ 1, 3, 4, 2]}
#=> {:keywords=>{:a=>1, :c=>2, :b=>3}, :authors=>[1, 3, 4, 2]}
unordered_hash.sort.to_h
#=> {:authors=>[1, 3, 4, 2], :keywords=>{:a=>1, :c=>2, :b=>3}}

【讨论】:

  • 虽然 OP 没有明确问题,但这个答案在技术上并不正确,但是混合嵌套级别(就像你对 Array 所做的那样)可能更有意义,以表明这不进行深度排序。这也将受益于一些解释。
【解决方案2】:

您可以使用 sort_by 构建自己的逻辑,但它会很快变得复杂

我建议你使用 gem deepsort

您没有提供太多数据,但这是我认为您拥有的示例。

require "deepsort"
require 'json'

tagindex = {
  keywords: { keyword3: "contents3", keyword2: "contents2", keyword1: "contents1"}, 
  authors: [ "author2",  "author1",  "author4",  "author3"]
}

puts JSON.pretty_generate(tagindex.deep_sort)

=>
{
  "authors": [
    "author1",
    "author2",
    "author3",
    "author4"
  ],
  "keywords": {
    "keyword1": "contents1",
    "keyword2": "contents2",
    "keyword3": "contents3"
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 2014-01-08
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多