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!

2 Answers 2

1
(microposts + pub_messages).sort! { |a,b| b[:time_ago] <=> a[:time_ago] }
Sign up to request clarification or add additional context in comments.

1 Comment

i forgot to mention, i tried doing that too but it doesn't seem to change anything. its still in asc order
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.