根据对象属性对对象数组进行排序

时间:2019-02-07 07:16:54

标签: ruby

我有一个像这样的数组:

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

我需要基于committed_date对这个数组进行排序。我该怎么办?

我是否必须循环编写一个自定义排序功能,或者Ruby是否提供了一些现成的功能?

1 个答案:

答案 0 :(得分:4)

使用sort_by

array.sort_by {|obj| obj.attribute}

或更简洁

array.sort_by(&:attribute)

以您的情况

array.sort_by {|obj| obj[:commit][:committed_date]}