Ruby - 按属性按降序排序对象数组

时间:2017-09-26 18:55:31

标签: ruby-on-rails json ruby sorting

我有这个Json对象数组

"students": [{
    "id": 1,
    "first_name": "John",
    "last_name": "Doe",
    "age": "14",
  }, {
    "id": 2,
    "first_name": "Victoria",
    "last_name": "Secret",
    "age": "9",
  }, {
    "id": 3,
    "first_name": "Jim",
    "last_name": "Morrison",
    "age": "16",
  }, {
    "id": 4,
    "first_name": "Jack",
    "last_name": "Daniels",
    "age": "7",
  },
  }]

我想在 DESC 顺序中的index.html.erb 按年龄排序中显示它们。我已经到了一半,我已经设法对它们进行排序,但不是按照DESC的顺序排序。这是我的循环

<% @classroom['students'].sort_by { |st| st['age'] }.each do |student| %>

这是我想要的结果:

16,  Jim,     Morrison
14,  John,    Doe
9,  Victoria, Secret
7,  Jack,     Daniels

这就是我得到的:

14,  John,    Doe
16,  Jim,     Morrison
7,  Jack,     Daniels
9,  Victoria, Secret

1 个答案:

答案 0 :(得分:1)

你错过了让年龄成为一个数字

@classroom['students'].sort_by { |st| -st['age'].to_i }

我添加了-,因为您希望它们按降序排列。否则

@classroom['students'].sort_by { |st| st['age'].to_i }.reverse