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}
.
我需要所有最小的键/值对。如果{'a'=> 1,'b'=> 1,'c'=> 2},预期结果应为{'a'=> 1,'b'=> 1}。
4 个解决方案
#1
9
[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}
#2
8
test.select { |_, v| v == test.values.min }
To make it more efficient:
为了提高效率:
min_val = test.values.min
test.select { |_, v| v == min_val }
#3
0
AS Per Given Your Data
根据您的数据
Run the following on your Ruby Console :-
在Ruby控制台上运行以下命令: -
test = {'a'=> 1, 'b'=> 2, 'c' => 0.4, 'd' => 0.32, 'e' => 0.03,
'f' => 0.02, 'g'=> 0.1}
Hash[*test.sort_by(&:last)[0]]
Output will be as per per your expectations
产量将按照您的预期
=> {"f"=>0.02}
#4
0
You can also achieve this without using a .min
method:
您也可以在不使用.min方法的情况下实现此目的:
def min_key_value_pair (test)
if test == {}
return nil
else
test = test.sort_by {|k, v| v}
test[0]
end
end
I had to do something similar for a class I am taking. We also had to return JUST THE KEY. for which you would do the same thing only return test[0][0]
Hope this was helpful!!!
我必须为我正在上课的课程做类似的事情。我们还必须返回JUST THE KEY。为什么你会做同样的事情只返回测试[0] [0]希望这是有帮助的!
#1
9
[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}
#2
8
test.select { |_, v| v == test.values.min }
To make it more efficient:
为了提高效率:
min_val = test.values.min
test.select { |_, v| v == min_val }
#3
0
AS Per Given Your Data
根据您的数据
Run the following on your Ruby Console :-
在Ruby控制台上运行以下命令: -
test = {'a'=> 1, 'b'=> 2, 'c' => 0.4, 'd' => 0.32, 'e' => 0.03,
'f' => 0.02, 'g'=> 0.1}
Hash[*test.sort_by(&:last)[0]]
Output will be as per per your expectations
产量将按照您的预期
=> {"f"=>0.02}
#4
0
You can also achieve this without using a .min
method:
您也可以在不使用.min方法的情况下实现此目的:
def min_key_value_pair (test)
if test == {}
return nil
else
test = test.sort_by {|k, v| v}
test[0]
end
end
I had to do something similar for a class I am taking. We also had to return JUST THE KEY. for which you would do the same thing only return test[0][0]
Hope this was helpful!!!
我必须为我正在上课的课程做类似的事情。我们还必须返回JUST THE KEY。为什么你会做同样的事情只返回测试[0] [0]希望这是有帮助的!