我要做一些相当复杂的排序。
给定一个哈希数组,我需要根据每个哈希键的值对数组内的哈希进行排序。
例如(以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中)的一部分的屏幕截图,目的是更好地说明我的意思:
“ >>
任何帮助将不胜感激。
谢谢!
我要做一些相当复杂的排序。给定一个哈希数组,我需要根据每个哈希键中的值对数组中的哈希排序。例如(以JSON格式给出):“ ...
您正在寻找Enumerable#sort_by。
您可以使用ruby sort_by方法(http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-sort_by)
如果有帮助的人,我的JSON是双重嵌套的