我有一些相当复杂的排序要做。
给定一个哈希数组,我需要根据每个哈希的键中的值对数组中的哈希进行排序。
例如(以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 中)的一部分的屏幕截图,以更好地说明我的意思:
如有任何帮助,我们将不胜感激。
谢谢!
最佳答案
您正在寻找 Enumerable#sort_by .
instruments.sort_by { |x| x["title"] }
关于ruby-on-rails - Ruby - 如何根据嵌套哈希项的值对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28585478/