【问题标题】:Ruby - How do I sort an array based on the value of nested hash items?Ruby - 如何根据嵌套哈希项的值对数组进行排序?
【发布时间】:2015-02-18 14:00:06
【问题描述】:

我有一些相当复杂的排序要做。

给定一个哈希数组,我需要根据每个哈希的键中的值对数组中的哈希进行排序。

例如(以 JSON 格式给出):

"instruments":[
{"id":1,"title":"Piano","token":"piano","count":13},
{"id":6,"title":"Bass Guitar","token":"bass","count":12},
{"id":11,"title":"Viola","token":"viola","count":12},
{"id":4,"title":"Synth","token":"synth","count":11},
{"id":3,"title":"Keyboard","token":"keyboard","count":9},
{"id":7,"title":"Saxophone","token":"saxophone","count":8},
{"id":12,"title":"Flute","token":"flute","count":8},
{"id":5,"title":"Drums","token":"drums","count":6},
{"id":2,"title":"Guitar","token":"guitar","count":5},
{"id":8,"title":"Violin","token":"violin","count":5},
{"id":9,"title":"Vocals","token":"vocals","count":4},
{"id":10,"title":"Cello","token":"cello","count":4}
]

这个 JSON 是 Rails 中 responds_with 的结果。在此之前,我想根据每个散列中 "title" 键的字母顺序在数组中切换这些散列。

这是 JSON 的一部分(在 Firebug 中)的屏幕截图,以更好地说明我的意思:

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby json


    【解决方案1】:

    您正在寻找Enumerable#sort_by

    instruments.sort_by { |x| x["title"] }
    

    【讨论】:

    • 哇,就这么简单!太棒了。
    【解决方案2】:

    您可以使用 ruby​​ sort_by 方法 (http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-sort_by)

    所以在你的情况下,仪器看起来像这样:

    instruments=[
    {"id"=>1,"title"=>"Piano","token"=>"piano","count"=>13},
    {"id"=>6,"title"=>"Bass Guitar","token"=>"bass","count"=>12},
    {"id"=>11,"title"=>"Viola","token"=>"viola","count"=>12},
    {"id"=>4,"title"=>"Synth","token"=>"synth","count"=>11},
    {"id"=>3,"title"=>"Keyboard","token"=>"keyboard","count"=>9},
    {"id"=>7,"title"=>"Saxophone","token"=>"saxophone","count"=>8},
    {"id"=>12,"title"=>"Flute","token"=>"flute","count"=>8},
    {"id"=>5,"title"=>"Drums","token"=>"drums","count"=>6},
    {"id"=>2,"title"=>"Guitar","token"=>"guitar","count"=>5},
    {"id"=>8,"title"=>"Violin","token"=>"violin","count"=>5},
    {"id"=>9,"title"=>"Vocals","token"=>"vocals","count"=>4},
    {"id"=>10,"title"=>"Cello","token"=>"cello","count"=>4}
    ]
    

    您可以使用它来按给定列排序(在您的情况下为“标题”)

     instruments.sort_by{|instrument| instrument["title"]}
    

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      如果它可以帮助任何人跟进,我的 JSON 是双重嵌套的

      products = [
      {:product=>{:id=>866468155, :code=>"TB2", :name=>"Thunderbird 2"}},
      {:product=>{:id=>805953484, :code=>"FAB1", :name=>"Rolls-Royce FAB 1"}},
      {:product=>{:id=>715919491, :code=>"TB1", :name=>"Thunderbird 1"}},
      {:product=>{:id=>767677594, :code=>"TB5", :name=>"Thunderbird 5"}},
      ]
      

      我可以使用,按名称排序,

      table.sort_by! { |x| x[:product][:name]}
      

      ...注意这也使用 !就地排序,而不是创建一个新数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-08
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-05
        相关资源
        最近更新 更多