AnApprentice
AnApprentice

Reputation: 111080

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?

Upvotes: 68

Views: 120709

Answers (6)

Eric Norcross
Eric Norcross

Reputation: 4306

In rails 4+

@list.sort_by(&:time_ago)

Upvotes: 15

DanneManne
DanneManne

Reputation: 21180

Just FYI, I don't see the point in moving the messages into a new list and then sorting them. As long as it is ActiveRecord it should be done directly when querying the database in my opinion.

It looks like you should be able to do it like this:

@messages = Message.includes(:replies).order("replies.created_at ASC")

That should be enough unless I have misunderstood the purpose.

Upvotes: 4

Mike Lewis
Mike Lewis

Reputation: 64177

 @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 }
}

Upvotes: 154

Dylan Markow
Dylan Markow

Reputation: 124469

You can also do @list.sort_by { |message| message.time_ago }

Upvotes: 6

grzuy
grzuy

Reputation: 5041

You could do:

@list.sort {|a, b| a[:time_ago] <=> b[:time_ago]}

Upvotes: 12

Spyros
Spyros

Reputation: 48706

Yes, you can use group_by :

http://api.rubyonrails.org/classes/Enumerable.html#method-i-group_by

Upvotes: 0

Related Questions