Ruby: How to find the key of the largest value in

2019-01-24 21:25发布

Hello I'm trying to find the largest value in my hash. I made a search in google and I found this code:

def largest_hash_key(hash)
  key = hash.sort{|a,b| a[1] <=> b[1]}.last
  puts key
end

hash = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
largest_hash_key(hash)

in this code "puts" prints the largest key and value e.x y300. So, how I can modify the code in order to find the largest value and put it's key in to_s variable?

标签: ruby hash max
5条回答
2楼-- · 2019-01-24 22:09

Sort the hash once instead of finding max. This way you can also get smallest etc.

def reverse_sort_hash_value(hash)
   hash = hash.sort_by {|k,v| v}.reverse
end

h = reverse_sort_hash_value(h)

Key of largest value

max = *h[0][0]

Get Key/Value of the smallest value

puts *h[h.length-1]

You can convert to hash using Hash[h.select { |k, v| v == max}] or using h.to_h

查看更多
爷的心禁止访问
3楼-- · 2019-01-24 22:10

Here is another way of doing what you want. This will find all the keys with the maximum value:

h = {"n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0, "z" => 300}          
max = h.values.max
output_hash = Hash[h.select { |k, v| v == max}]
puts "key(s) for the largest value: #{output_hash.keys}"

#=>key(s) for the largest value: ["y", "z"]
查看更多
欢心
4楼-- · 2019-01-24 22:11

This is O(n):

h = {"n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0}
key_with_max_value = h.max_by { |k, v| v }[0] #=> "y"
查看更多
Luminary・发光体
5楼-- · 2019-01-24 22:19

You can modify your method's first statement to

key = hash.sort{|a,b| a[1] <=> b[1]}.last[0]

Hash.sort returns an array of key-value pairs. last gets you the key-value pair with the largest value. Its first element is the corresponding key.

查看更多
淡お忘
6楼-- · 2019-01-24 22:25

I think it is not a good idea to use something you find on google and tweak it until it somehow runs. If we develop software, we should do something that we understand.

A Hash is optimized to lookup a value by key. It is not optimized to sort the values or find by properties of the values. So the data structure is not helpful for your problem. Other data structures like trees or even arrays may be better.

But if you want to use a hash because of some other reasons, of course it is possible. Somehow you just need to loop over the whole hash.

The algorithm is quite easy: loop over the whole hash and check if the value is bigger and the previous biggest value:

max_value = 0  # or -Infinity if you have negative values
key_for_max_value = nil

hash.each_pair do | key, value |
  if value > max_value
    max_value = value
    key_for_max_value = key
  end
end
puts "The largest value is #{max_value} and it is has the key #{key_for_max_value}"

Some of the other solutions use tricks like to sort the array, but this only hides the complexity.

查看更多
登录 后发表回答