ColdTree ColdTree - 1 year ago 54
Ruby Question

Rails, Ruby, how to sort an Array?

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

@messages.each do |message|

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

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

Answer Source
 @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 ={|m| 
  {:id =>, :title => m.title, :time_ago => m.replies.first.created_at }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download