General_9
General_9

Reputation: 2319

Order an array of objects by descending order of created_at date

I have an array of Comment objects retrieved from Mongoid. How do I sort an array by created_at date in descending order.

I have tried the code below:

all_comments = []
    all_comments.concat(question_comments).concat(answer_comments).sort_by { |x| -x[:created_at] }

I get the following error:

undefined method `-@' for 2013-08-17 10:34:46 UTC:Time

Upvotes: 2

Views: 1868

Answers (1)

Santhosh
Santhosh

Reputation: 29094

You can use desc method.

all_comments.concat(question_comments).concat(answer_comments).desc(:created_at)

If the result set is an Array, you can use sort

all_comments.concat(question_comments).concat(answer_comments).sort { |x,y| y.created_at <=> x.created_at }

Upvotes: 3

Related Questions