How to pick top 5 values from a hash?
arrays, hash, hashmap, ruby, sorting
Solution
You can do
@objects = {1=>57, 4=>12, 3=>9, 5=>3, 55=>47, 32=>39, 17=>27, 29=>97, 39=>58}
@objects.sort_by { |_, v| -v }[0..4].map(&:first)
# => [29, 39, 1, 55, 32]
@objects.sort_by { |_, v| -v }.first(5).map(&:first)
# => [29, 39, 1, 55, 32]
Problem
I have a hash of ids and their scores, it's something like this: ``` @objects = {1=>57, 4=>12, 3=>9, 5=>3, 55=>47, 32=>39, 17=>27, 29=>97, 39=>58} ``` How can I pick the top five and drop the rest ? I'm doing this: ``` @orderedObject = @objects.sort_by {|k,v| v}.reverse =>[[29, 97], [39, 58], [1, 57], [55, 47], [32, 39], [17, 27], [4, 12], [3, 9], [5, 3]] ``` Then I do this: only Keys of the `@orderedObjects`: ``` @keys = @orderedObject.map { |key, value| key } ``` which gives me: ``` =>[29, 39, 1, 55, 32, 17, 4, 3, 5] ``` ALL I need is `[29, 39, 1, 55, 32]` the first 5 indexes. But I'm stuck I don't know how to do this.