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

时间:2022-01-21 16:45:04

I have this Json array of objects

我有这个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",
  },
  }]

I want to display them in my index.html.erb sorted by age in DESC order. I'm half way there, I have manage to sort them, however not in exact DESC order. This is my loop

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

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

This is the result I want:

这是我想要的结果:

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

This is what I get instead:

这就是我得到的:

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

1 个解决方案

#1


1  

You missed to make the age a number

你错过了把年龄变成一个数字

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

I added a - because you want them in descending order. Otherwise

我添加了一个 - 因为你想要它们按降序排列。除此以外

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

#1


1  

You missed to make the age a number

你错过了把年龄变成一个数字

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

I added a - because you want them in descending order. Otherwise

我添加了一个 - 因为你想要它们按降序排列。除此以外

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