Hey I have an array where each element is a hash containing a few values and a count.
result = [
{"count" => 3,"name" => "user1"},
{"count" => 10,"name" => "user2"},
{"count" => 10, "user3"},
{"count" => 2, "user4"}
]
I can sort the array by count as follows:
result = result.sort_by do |r|
r["count"]
end
Now I want to be able to retrieve the top n entries based on count (not just first(n)) Is there an elegant way to do this?
So as an example, let n = 1 I would expect a result set of.
[{"count" => 10,"name" => "user2"}, {"count" => 10, "user3"}]
since I asked for all entries with the highest score.. if I asked for top 2 highest scores I’d get
[{"count" => 10,"name" => "user2"}, {"count" => 10, "user3"}, {"count" => 3, "user1"}]
Enumerable#group_byto the rescue (as usual):Most of the work is done by the
group_by. Thesort_bysimply lines things up so thatfirst(2)will pick off the groups you want. Thenmapwithlastwill extract the count/name hashes that you started with and the finalflattenwill clean up the extra left over arrays.