Skip to content

Instantly share code, notes, and snippets.

@fabrizioc1
Created June 19, 2012 18:14
Show Gist options
  • Save fabrizioc1/2955689 to your computer and use it in GitHub Desktop.
Save fabrizioc1/2955689 to your computer and use it in GitHub Desktop.
Get top n elements from ruby array of hash values
# 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"}]
@reedjosh1
Copy link

I landed here, so... result.sort_by { |r| [r['count'], r['name']] } is pretty much what you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment