3

I have a hash which is something like this

{"red" => 3, "blue" => 1, "yellow" => 3, "green" => 1, "black" => 4}

I want to sort and display the top three colors in the order of the hash's values i.e

["black", "red", "yellow"]

I tried to do something like sort_by { |x,y| h[x] <=> h[y] } and max_by { |x,y| h[x] }, but I only get ["black"]. How do you get the top three occurrences?

sawa
  • 165,429
  • 45
  • 277
  • 381
gkolan
  • 1,571
  • 2
  • 20
  • 37

3 Answers3

8

As variant:

h = {"green"=>1, "red"=>3, "yellow"=>3, "blue"=>1, "black"=>4}
h.sort_by{ |color, n| -n }.map(&:first).take(3) #=> ["black", "red", "yellow"]
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
3

Here's one way to do it.

colors = {"red"=>3, "blue"=>1, "yellow"=>3, "green"=>1, "black"=>4}
colors.sort { |a, b| b[1] <=> a[1] }.map { |a| a[0] }.take(3)
Blake Taylor
  • 9,217
  • 5
  • 38
  • 41
2

This seems to do it.

sortedColours = colours.keys
 .sort {|keyA, keyB| colours[keyB] - colours[keyA] }

Riddle.

If you want the top 3, just slice off the first 3.

firstThreeColours = sortedColours[0,3]
alex
  • 479,566
  • 201
  • 878
  • 984