2

I have an array of hashes:

[ 
  {
    :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"
  }
]

I want to sort it in the following order:

  1. First sort is based on to
  2. Second sort is based on from
  3. Third sort is based on organisation name
  4. Finally, sort based on title

Can anyone help me sort the array of hashes?

1
  • 1
    Where does nil of :to=>nil go? Please answer with edit. Commented Jul 31, 2018 at 2:14

1 Answer 1

11
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"}]

See Array#<=>, particularly the third paragraph of the doc, and Enumerable#sort_by.

Sign up to request clarification or add additional context in comments.

1 Comment

1+ for passing number of arguments to sort_by

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.