Rails, Ruby, how to sort an Array?

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


in my rails app I'm creating an array like so:

@messages.each do |message|

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

After making this array I would like to then sort it by time_ago ASC order, is that possible?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

it defaults to ASC, however if you wanted DESC you can do:

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

Also it seems like you are trying to build the list from @messages. You can simply do:

@list = @messages.map{|m| 
  {:id => m.id, :title => m.title, :time_ago => m.replies.first.created_at }
}

Solution 2 - Ruby on-Rails

In rails 4+

@list.sort_by(&:time_ago)

Solution 3 - Ruby on-Rails

You could do:

@list.sort {|a, b| a[:time_ago] <=> b[:time_ago]}

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

Just FYI, I don't see the point in moving the messages into a new list and then sorting them. As long as it is ActiveRecord it should be done directly when querying the database in my opinion.

It looks like you should be able to do it like this:

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

That should be enough unless I have misunderstood the purpose.

Solution 6 - Ruby on-Rails

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnApprenticeView Question on Stackoverflow
Solution 1 - Ruby on-RailsMike LewisView Answer on Stackoverflow
Solution 2 - Ruby on-RailsEric NorcrossView Answer on Stackoverflow
Solution 3 - Ruby on-RailsgrzuyView Answer on Stackoverflow
Solution 4 - Ruby on-RailsDylan MarkowView Answer on Stackoverflow
Solution 5 - Ruby on-RailsDanneManneView Answer on Stackoverflow
Solution 6 - Ruby on-RailsSpyrosView Answer on Stackoverflow