Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, Ruby, how to sort an Array?

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?

like image 789
AnApprentice Avatar asked Apr 21 '11 03:04

AnApprentice


2 Answers

 @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 }
}
like image 109
Mike Lewis Avatar answered Oct 28 '22 11:10

Mike Lewis


In rails 4+

@list.sort_by(&:time_ago)
like image 14
Eric Norcross Avatar answered Oct 28 '22 09:10

Eric Norcross