【问题标题】:How to sort Ruby Hash with dynamic keys如何使用动态键对 Ruby 哈希进行排序
【发布时间】:2015-11-07 05:10:22
【问题描述】:

如果需要,我想了解如何使用键和/或它们的子键对 ruby​​ 哈希进行排序。例如:

带有 sub_hashs 的哈希示例

two_hash = {
  'a' => {'displayName' => "A", 'name' => "Apple", 'Association' => {'id' => '1', 'type' => 'B2'}},
  'c' => {'displayName' => "D", 'name' => "Banana", 'Association' => {'id' => '1', 'type' => 'B3'}},
  'b' => {'displayName' => "C", 'name' => "Orange", 'Association' => {'id' => '1', 'type' => 'B1'}},
  'd' => {'displayName' => "B", 'name' => "Kiwi", 'Association' => {'id' => '1', 'type' => 'B4'}}
}

目前我可以这样排序,调用并指定要排序的键/子键。

puts (two_hash.sort_by {|h, k| k['displayName']})
puts (two_hash.sort_by {|h, k| k['Association']['type']})

我想将它转换为 proc 并在我想要输入子键时使用它。

我想要它,所以我可以传入一个键或子键,它会为我排序。像这样,有没有办法在 Ruby 中做到这一点?

sort_stuff_method(two_hash, ['displayname'])
sort_stuff_method(two_hash, ['Association']['type'])

【问题讨论】:

    标签: ruby sorting hash key


    【解决方案1】:

    这是一种方法:

    def sort_em(h, *nested_keys)
      h.sort_by { |k,v| nested_keys.reduce(v) { |g,k| g[k] } }
    end
    
    sort_em(two_hash, 'displayName')
      #=> [["a", {"displayName"=>"A", "name"=>"Apple",
      #           "Association"=>{"id"=>"1", "type"=>"B2"}}],
      #    ["d", {"displayName"=>"B", "name"=>"Kiwi",
      #           "Association"=>{"id"=>"1", "type"=>"B4"}}],
      #    ["b", {"displayName"=>"C", "name"=>"Orange",
      #           "Association"=>{"id"=>"1", "type"=>"B1"}}],
      #    ["c", {"displayName"=>"D", "name"=>"Banana",
      #           "Association"=>{"id"=>"1", "type"=>"B3"}}]] 
    
    sort_em(two_hash, 'Association', 'type')
      #=> [["b", {"displayName"=>"C", "name"=>"Orange",
      #           "Association"=>{"id"=>"1", "type"=>"B1"}}],
      #    ["a", {"displayName"=>"A", "name"=>"Apple",
      #           "Association"=>{"id"=>"1", "type"=>"B2"}}],
      #    ["c", {"displayName"=>"D", "name"=>"Banana",
      #           "Association"=>{"id"=>"1", "type"=>"B3"}}],
      #    ["d", {"displayName"=>"B", "name"=>"Kiwi",
      #           "Association"=>{"id"=>"1", "type"=>"B4"}}]] 
    

    这当然适用于任意数量的嵌套键。

    【讨论】:

      【解决方案2】:

      这是你要找的吗,

      def sort_stuff_method(input_hash, sort_key, sort_sub_key=nil)
        input_hash.sort_by{|h,k| sort_sub_key.nil? ? k[sort_key] : k[sort_key][sort_sub_key]}
      end
      

      你可以这样使用它,

      sort_stuff_method(input_hash, 'displayName')
      sort_stuff_method(input_hash, 'Association', 'Type')
      

      【讨论】:

      • 谢谢。这正是我想要的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2011-08-12
      • 2012-05-01
      相关资源
      最近更新 更多