Rails,Ruby,如何对数组进行排序?

问题描述:

在我的 rails 应用程序中,我正在创建一个数组,如下所示:

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

制作这个数组后,我想按 time_ago ASC 顺序对其进行排序,这可能吗?

After making this array I would like to then sort it by time_ago ASC order, is that possible?

 @list.sort_by{|e| e[:time_ago]}

它默认为 ASC,但是如果你想要 DESC,你可以这样做:

it defaults to ASC, however if you wanted DESC you can do:

 @list.sort_by{|e| -e[:time_ago]}

此外,您似乎正在尝试从 @messages 构建列表.你可以简单地做:

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