2

I have this Json array of objects

"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

<% @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
ltdev
  • 4,037
  • 20
  • 69
  • 129

1 Answers1

5

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
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • Correct, well spotted! One additional question if thats ok.. Is it considered best practice to have the `sort_by` block in my view and then append the `.each` to loop through the objects, or there's a more elegant way to do it? just for better readability – ltdev Sep 26 '17 at 19:03
  • I'd leave the `sort_by` stuff in the action and in the view just `@students.each do` – Ursus Sep 26 '17 at 19:04
  • Sorry just one more question. Each student has a birthdate attribute as this example `1997-09-26T10:40:00.000+01:00`, How can I convert the date to human readable format? I tried `<%= student['dob'].strftime('%d-%m-%Y, %H:%M') %>`, but this breaks the code – ltdev Sep 26 '17 at 19:26
  • `undefined method `strftime' for "2017-09-26T20:40:00.000+01:00":String` – ltdev Sep 26 '17 at 19:28
  • 1
    @Ursus, Hey! Good answer, but, as I know - using `#sort_by` with `#reverse` - should works faster ;) – Oleksandr Holubenko Sep 26 '17 at 19:31
  • Sure, that's valid too. – Ursus Sep 26 '17 at 19:31
  • I get only the date (not time) as a mysql format, like 2017-09-26, although I have same format set as you – ltdev Sep 26 '17 at 19:32
  • 1
    Oh, my fault. Try this one `<%= Date.parse(student['dob']).strftime('%d-%m-%Y, %H:%M') %>` – Ursus Sep 26 '17 at 19:34
  • Worked with DateTime correct. `DateTime.parse(student['dob']).strftime('%d-%m-%Y, %H:%M')` – ltdev Sep 27 '17 at 07:33