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?
Sort the hash once instead of finding max. This way you can also get smallest etc.
Key of largest value
Get Key/Value of the smallest value
You can convert to hash using
Hash[h.select { |k, v| v == max}]
or usingh.to_h
Here is another way of doing what you want. This will find all the keys with the maximum value:
This is O(n):
You can modify your method's first statement to
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.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:
Some of the other solutions use tricks like to sort the array, but this only hides the complexity.