Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}.

like image 873
Galet Avatar asked Jun 05 '14 11:06

Galet


2 Answers

[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}
like image 83
sawa Avatar answered Oct 12 '22 23:10

sawa


test.select { |_, v| v == test.values.min }

To make it more efficient:

min_val = test.values.min
test.select { |_, v| v == min_val }
like image 10
Uri Agassi Avatar answered Oct 13 '22 00:10

Uri Agassi