1

I have an array like so:

[
  {
    "name": "aabb",
    "commit": {
      "id": "1",
      "message": "aabb ",
      "committed_date": "2018-04-04T15:11:04.000+05:30",
      "committer_name": "ak",
      "committer_email": "[email protected]"
    },
    "protected": false
  },
  {
    "name": "aacc",
    "commit": {
      "id": "2",
      "message": "aacc ",
      "committed_date": "2018-02-04T15:11:04.000+05:30",
      "committer_name": "ak",
      "committer_email": "[email protected]"
    },
    "protected": false
  },
  {
    "name": "aadd",
    "commit": {
      "id": "3",
      "message": "aadd ",
      "committed_date": "2018-04-01T15:11:04.000+05:30",
      "committer_name": "ak",
      "committer_email": "[email protected]"
    },
    "protected": false
  }
]

I need to sort this array based on committed_date. How do I do that?

Do I have to loop and write a custom sorting function or does Ruby offers something out-of-box?

8
  • 3
    arr.sort_by { |h| h[:commit][:committed_date] } #=> [{:name=>"aacc",...}, {:name=>"aadd",...}, {:name=>"aabb",...}]. There is no need to convert the date to a date object. This is a pure-Ruby question so you don't need the Rails tag. Commented Feb 7, 2019 at 7:21
  • @CarySwoveland - Please post your solution as answer Commented Feb 7, 2019 at 7:36
  • 2
    This is Cary's dad. Sorry, he's gone to bed. Commented Feb 7, 2019 at 7:45
  • @CarySwoveland should remember to log out. Dads are sneaky. Commented Feb 7, 2019 at 7:45
  • 2
    @CarySwoveland That applies if they're all in the same +05:30 time zone, otherwise you need to do something to standardize the zones. Commented Feb 7, 2019 at 8:09

1 Answer 1

2

Using sort_by

array.sort_by {|obj| obj.attribute}

Or more concise

array.sort_by(&:attribute)

In your case

array.sort_by {|obj| obj[:commit][:committed_date]}
Sign up to request clarification or add additional context in comments.

1 Comment

I went ahead with this solution. Thanks Umar and Cary.

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.