karan karan - 1 year ago 92
Ruby Question

How to get min key value pair in hash

I want to fetch the lowest value in the hash.


test = {'a'=> 1, 'b'=> 2, 'c' => 0.4, 'd' => 0.32, 'e' => 0.03, 'f' => 0.02, 'g'=> 0.1}

Expected result:

{'f'=> 0.02}

How can I get the expected result?

I need all minimum key/value pairs. if
the expected result should be

Answer Source
[test.min_by{|k, v| v}].to_h

Answer to the question after it has been changed:

test.group_by{|k, v| v}.min_by{|k, v| k}.last.to_h # => {"f"=>0.02}


test.group_by(&:last).min_by(&:first).last.to_h # => {"f"=>0.02}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download