Rails,Ruby,如何对数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5739158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails, Ruby, how to sort an Array?
提问by AnApprentice
in my rails app I'm creating an array like so:
在我的 rails 应用程序中,我正在创建一个数组,如下所示:
@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?
制作这个数组后,我想按 time_ago ASC 顺序对其进行排序,这可能吗?
回答by Mike Lewis
@list.sort_by{|e| e[:time_ago]}
it defaults to ASC, however if you wanted DESC you can do:
它默认为 ASC,但是如果您想要 DESC,您可以执行以下操作:
@list.sort_by{|e| -e[:time_ago]}
Also it seems like you are trying to build the list from @messages. You can simply do:
此外,您似乎正在尝试从@messages. 你可以简单地做:
@list = @messages.map{|m|
{:id => m.id, :title => m.title, :time_ago => m.replies.first.created_at }
}
回答by grzuy
You could do:
你可以这样做:
@list.sort {|a, b| a[:time_ago] <=> b[:time_ago]}
回答by Eric Norcross
In rails 4+
在导轨中 4+
@list.sort_by(&:time_ago)
回答by Dylan Markow
You can also do @list.sort_by { |message| message.time_ago }
你也可以这样做 @list.sort_by { |message| message.time_ago }
回答by DanneManne
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.
仅供参考,我认为将消息移动到新列表中然后对其进行排序没有意义。只要是ActiveRecord,我觉得在查询数据库的时候就应该直接做。
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.
除非我误解了目的,否则这应该足够了。
回答by Spyros
Yes, you can use group_by :
是的,您可以使用 group_by :
http://api.rubyonrails.org/classes/Enumerable.html#method-i-group_by
http://api.rubyonrails.org/classes/Enumerable.html#method-i-group_by

