karan karan - 3 months ago 9
Ruby Question

How to get min key value pair in hash

I want to fetch the lowest value in the hash.

Input:

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
{'a'=>1,'b'=>1,'c'=>2}
the expected result should be
{'a'=>1,'b'=>1}
.

Answer
[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}

or

test.group_by(&:last).min_by(&:first).last.to_h # => {"f"=>0.02}