返回具有重复值的哈希的最小值

时间:2017-02-01 02:37:34

标签: ruby

例如,如果我有哈希{"a" => 1, "b" => 2, "c" => 1},我想要["a", "c"]

我可以hash.min_by{|k,v| v},但只返回第一个匹配项("a"=>1)。

如何让它识别重复项并返回{"a"=> 1, "c"=> 1}

3 个答案:

答案 0 :(得分:7)

对于哈希来说,这个操作有点不寻常,所以它不是很整洁:

min_value = hash.values.min
min_pairs = hash.select { |k, v| v == min_value }

答案 1 :(得分:4)

{"a" => 1, "b" => 2, "c" => 1}.group_by(&:last).min.last.map(&:first)
# => ["a", "c"]

{"a" => 1, "b" => 2, "c" => 1}.group_by(&:last).min.last.to_h.keys
# => ["a", "c"]

答案 2 :(得分:1)

你可以用任何语言写FORTRAN! :)

它的优点是只需要1次通过:

hash = {"a" => 1, "b" => 2, "c" => 1}

min = Float::INFINITY
values_for_min = []

hash.each do |key, value|
  case value <=> min
  when 0
    values_for_min << key
  when -1
    min = value
    values_for_min = [key]
  end
end

p min
#=> 1
p values_for_min
#=> ["a", "c"]