我有一个哈希数组:
[
{
:title=>"Working as a SSE",
:organisation=>{:id=>428, :name=>"google"},
:from=>"2018-6-1",
:to=>nil
}, {
:title=>"Concatenate two video files to single video in players",
:organisation=>{:id=>197, :name=>"UNFPA"},
:from=>"2014-1-1",
:to=>"2015-12-1"
}, {
:title=>"Highcharts Demo",
:organisation=>{:id=>6, :name=>"UNDFS"},
:from=>"2016-1-1",
:to=>"2017-6-1"
}, {
:title=>"Working as a Judicial Affairs",
:organisation=>{:id=>427, :name=>"swtp"},
:from=>"2017-1-1",
:to=>"2018-6-1"
}
]
我想按以下顺序对其进行排序:
to
from
organisation name
title
任何人都可以帮助我对哈希数组进行排序吗?
答案 0 :(得分:8)
arr = [
{
:title=>"Working as a SSE",
:organisation=>{:id=>428, :name=>"google"},
:from=>"2018-6-1",
:to=>"2017-6-1"
}, {
:title=>"Concatenate two video files to single video in players",
:organisation=>{:id=>197, :name=>"UNFPA"},
:from=>"2014-1-1",
:to=>"2015-12-1"
}, {
:title=>"Highcharts Demo",
:organisation=>{:id=>6, :name=>"UNDFS"},
:from=>"2016-1-1",
:to=>"2017-6-1"
}, {
:title=>"Working as a Judicial Affairs",
:organisation=>{:id=>427, :name=>"swtp"},
:from=>"2017-1-1",
:to=>"2018-6-1"
}
]
arr.sort_by { |h| [h[:to], h[:from], h[:organisation][:name], h[:title]] }
#=> [{:title=>"Concatenate two video files to single video in players",
# :organisation=>{:id=>197, :name=>"UNFPA"},
# :from=>"2014-1-1",
# :to=>"2015-12-1"},
# {:title=>"Highcharts Demo",
# :organisation=>{:id=>6, :name=>"UNDFS"},
# :from=>"2016-1-1",
# :to=>"2017-6-1"},
# {:title=>"Working as a SSE",
# :organisation=>{:id=>428, :name=>"google"},
# :from=>"2018-6-1",
# :to=>"2017-6-1"},
# {:title=>"Working as a Judicial Affairs",
# :organisation=>{:id=>427, :name=>"swtp"},
# :from=>"2017-1-1",
# :to=>"2018-6-1"}]
请参见Array#<=>(尤其是文档的第三段)和Enumerable#sort_by。