Reputation: 33
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?
and is there any way in which i can change the order i between, i mea any callbacks available for this. Please suggest.
Upvotes: 0
Views: 41
Reputation: 44685
Just do:
@list.sort_by {|hash| hash[:time_ago]}
This will not alter the original array, so you'll need to assign it to some variable. If you want to sort it in place, use banged version sort_by!
instead.
Just a note: There is a potential N+1 problem in your code, as your loop may execute an extra SQL query on each repetition. So remember to call @messages.includes(:replies)
before looping. Also there might be much faster solution with a proper SQL query. However you need to specify why you want time_age to be the first value for messages in the database - could it be that you want the earliest message instead?
Upvotes: 1
Reputation: 11116
final_array = @list.sort {|a,b| a[:time_ago] <=> b[:time_ago]}
should work
Upvotes: 1