Rails, Ruby, how to sort an array?

in my rails application I create an array like this:

@messages.each do |message| @list << { :id => message.id, :title => message.title, :time_ago => message.replies.first.created_at } end 

After creating this array, I would like to sort it in order by ASC time, is this possible?

+55
ruby ruby-on-rails ruby-on-rails-3
Apr 21 2018-11-11T00:
source share
6 answers
  @list.sort_by{|e| e[:time_ago]} 

ASC is used by default, however if you want DESC you can do:

  @list.sort_by{|e| -e[:time_ago]} 

It also seems like you are trying to create a list from @messages . You can simply do:

 @list = @messages.map{|m| {:id => m.id, :title => m.title, :time_ago => m.replies.first.created_at } } 
+117
Apr 21 2018-11-11T00:
source share

You can do:

 @list.sort {|a, b| a[:time_ago] <=> b[:time_ago]} 
+10
Apr 21 2018-11-11T00:
source share

You can also do @list.sort_by { |message| message.time_ago } @list.sort_by { |message| message.time_ago }

+5
Apr 21 2018-11-11T00:
source share

Just FYI, I see no reason to move messages to a new list and sort them. While this is ActiveRecord, this should be done directly when querying the database in my opinion.

It looks like you should do it like this:

 @messages = Message.includes(:replies).order("replies.created_at ASC") 

This should be enough if I did not understand this goal.

+3
Apr 21 '11 at 4:22
source share

In rails 4+

 @list.sort_by(&:time_ago) 
+2
Jun 24 '16 at 4:38
source share
+1
Apr 21 '11 at 3:26
source share



All Articles