Charles Charles - 3 months ago 6
Ruby Question

How to get the highest and the lowest points in the hash?

@participants[id] = {nick: nick, points: 1}
=> {"1"=>{:nick=>"Test", :points=>3}, "30"=>{:nick=>"AnotherTest", :points=>5}, "20"=>{:nick=>"Newtest", :points=>3}}

I want my the lowest points
(ID: 1 and 20)
. How do I get the lowest points go first and then ID 30 go last?


If you use Enumerable#max_by() or Enumerable#min_by() you can do following;

data = {
 "1"  => {nick: "U1", points: 3}, 
 "30" => {nick: "U30", points: 5}, 
 "20" => {nick: "U20", points: 3}

max_id, max_data = data.max_by {|k,v| v[:points]}

puts max_id # => 30
puts max_data # => {nick: "U30", points: 5}

Same thing works with #min_by() and if you want to get back Hash you do this:

minimal = Hash[*data.min_by {|k,v| v[:points]}]
puts minimal # => {"1"=>{:nick=>"U1", :points=>3}}

Functions min_by() and max_by() will always return one record. If you want to get all records with same points then you have to use min / max data an do another "lookup" like this:

min_id, min_data = data.min_by {|k,v| v[:points]}
all_minimal = {|k,v| v[:points] == min_data[:points]}

puts all_minimal
# => {"1"=>{:nick=>"U1", :points=>3}, "20"=>{:nick=>"U20", :points=>3}}