0

ive been trying to sort an array in desc order but have been having trouble doing so.

i have...

microposts = Micropost.from_users_followed_by(self)
pub_messages = PubMessage.find_pub_messages_for(self.id)
(microposts + pub_messages).sort! { |a,b| a[:time_ago] <=> b[:time_ago] }

however the last line returns everything in ascending order. doing

.reverse

fixes it, but i heard it's not very efficient to do so. i tried doing

(microposts + pub_messages).sort! { |a,b| -a[:time_ago] <=> -b[:time_ago] }

but it gives an error that it can't find -@

i tried

(microposts + pub_messages).sort! { |a,b| b[:time_ago] <=> a[:time_ago] }

but it doesn't change it either (i swapped b and a around). what am i doing wrong? in the meantime, when i do the methods

find_pub_messages_for and from_users_followed_by

i do something like

default_scope order: 'pub_messages.created_at DESC'
default_scope order: 'microposts.created_at DESC'

in my models when i retrieve them. however is that a waste? because in the end, im sorting them again based on both microposts and pub_messages as seen in the line

(microposts + pub_messages).sort! { |a,b| a[:time_ago] <=> b[:time_ago] }

thanks a bunch!

4

2 回答 2

1
(microposts + pub_messages).sort! { |a,b| b[:time_ago] <=> a[:time_ago] }
于 2012-05-30T21:49:24.507 回答
1

i finally got it to work. i had to do...

(microposts + pub_messages).sort! { |a,b| b[:created_at] <=> a[:created_at] }

apparently :time_ago didn't work for me in sorting

于 2012-05-31T21:01:00.770 回答