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}
.
[test.min_by{|k, v| v}].to_h
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}
test.select { |_, v| v == test.values.min }
To make it more efficient:
min_val = test.values.min
test.select { |_, v| v == min_val }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With