【问题标题】:Sort array that's inside an array of hashes [closed]对哈希数组中的数组进行排序[关闭]
【发布时间】:2022-06-21 23:25:01
【问题描述】:

我是 ruby​​ 的新手,并试图找出一种方法来对散列数组中的数组进行排序。任何帮助将不胜感激。

输入是-

templates:
    - name: 'template1'
      expiry_days: 365
      certificate_authorities:
        - Issuer CA 04
        - Issuer CA 01
    - name: 'template2'
      expiry_days: 365
      certificate_authorities:
        - Issuer CA 05
        - Issuer CA 03 

预期的 o/p 是-

templates:
    - name: 'template1'
      expiry_days: 365
      certificate_authorities:
        - Issuer CA 01
        - Issuer CA 04
    - name: 'template2'
      expiry_days: 365
      certificate_authorities:
        - Issuer CA 03
        - Issuer CA 05 

请注意,certificate_authorities 在 o/p 中排序。

【问题讨论】:

  • 能否提供实际代码,而不是代码的抽象视图?

标签: ruby


【解决方案1】:

假设你有这个哈希:

hash = {
  templates: [
    {
      name: 'template1',
      expiry_days: 365,
      certificate_authorities: [
        '- Issuer CA 04',
        '- Issuer CA 01'
      ]
    },
    {
      name: 'template2',
      expiry_days: 365,
      certificate_authorities: [
        '- Issuer CA 05',
        '- Issuer CA 03'
      ]
    }
  ]
}

你可以这样修改:

hash.transform_values! do |templates|
  templates.map! do |template|
    template[:certificate_authorities].sort!
    template
  end
end

现在你的哈希看起来像这样:

{:templates=>
  [{:name=>"template1",
    :expiry_days=>365,
    :certificate_authorities=>["- Issuer CA 01", "- Issuer CA 04"]},
   {:name=>"template2",
    :expiry_days=>365,
    :certificate_authorities=>["- Issuer CA 03", "- Issuer CA 05"]}]}

请记住,您完全修改了内存中现有的对象:

hash.object_id
=> 220

hash.transform_values! do |templates|
  templates.map! do |template|
    template[:certificate_authorities].sort!
    template
  end
end

hash.object_id
=> 220

要不修改现有对象,而是创建具有转换(排序)值的新对象,您可以使用 :transform_values 方法而不是 transform_values!

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2014-05-30
    • 2016-11-16
    • 2012-01-21
    • 1970-01-01
    • 2014-03-05
    • 2015-04-08
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多