排序数组和哈希的红宝石哈希

时间:2019-06-20 17:15:33

标签: arrays ruby sorting hash

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

我有

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

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

2 个答案:

答案 0 :(得分: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}}

答案 1 :(得分:1)

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

我建议您使用宝石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"
  }
}