Created
June 19, 2012 18:14
-
-
Save fabrizioc1/2955689 to your computer and use it in GitHub Desktop.
Get top n elements from ruby array of hash values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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"}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I landed here, so...
result.sort_by { |r| [r['count'], r['name']] }
is pretty much what you want.