Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick top 5 values from a hash?

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.

like image 796
0bserver07 Avatar asked Jun 04 '14 18:06

0bserver07


2 Answers

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]
like image 122
Arup Rakshit Avatar answered Oct 09 '22 22:10

Arup Rakshit


May i suggest this more verbose requires ruby > 1.9

Hash[@objects.sort_by{|k,v| -v}.first(5)].keys
like image 44
Abs Avatar answered Oct 09 '22 23:10

Abs