How to find the key of the largest value hash?
This will return max hash key-value pair depending on the value of hash elements:
def largest_hash_key(hash)
hash.max_by{|k,v| v}
end
How do I get the maximum value of a hash in Ruby?
I would use the max
method on the values
of the hash:
{a: 1, b: 2}.values.max
Ruby - find the key(s) of the largest value(s) of a hash
If you want all pairs, I would do something like
max = my_hash.values.max
Hash[my_hash.select { |k, v| v == max}]
Finding the largest value in a nested hash
game_hash[:home][:players].max_by { |_name, stats| stats[:shoe] }.last[:shoe]
#=> 19
How to find the max value in an array of hashes?
You can do this with group_by
and max
:
arr.group_by { |x| x[:total] }.max.last
Find maximum value of values in hash where key value in array
A simple way is this:
AvailableDomains.map { |k| object[k.to_sym] }.max
Here's another way to do it:
object.with_indifferent_access.values_at(*AvailableDomains).max
If the array contained symbols, the with_indifferent_access would be unnecessary, but it's used here so that the Array's strings can match the hash's symbol keys.
Find the highest value in an array of hashes in Ruby
You can use max_by
method
students = [ { name: "Mary Jones", test_score: 80, sport: "soccer" }, { name: "Bob Kelly", test_score: 95, sport: "basketball" }, { name: "Kate Saunders", test_score: 99, sport: "hockey" }, { name: "Pete Dunst", test_score: 88, sport: "football" } ]
students.max_by{|k| k[:test_score] }
#=> {:name=>"Kate Saunders", :test_score=>99, :sport=>"hockey"}
students.max_by{|k| k[:test_score] }[:name]
#=> "Kate Saunders"
getting the largest value from a hash that is the value of another hash?
hash = {:foo =>{"string0"=>1, "string1"=>2}, :bar => {"string0"=>3, "string1"=>4}}
Hash[*hash.max_by { |_k, v| v['string0'] }]
#=> {:bar=>{"string0"=>3, "string1"=>4}}
To get the actual value:
hash.map { |_k, v| v['string0'] }.max
#=> 3
Related Topics
Error Install Rubyracer with Error "Invalid Gem: Package Is Corrupt"
Installing Rmagick Gem -- Can't Find Magickwand.H
Select Checkbox Pass Array in Ruby on Rails
Ruby String Split with Terminal Strings Empty
Consequences of Implementing To_Int and To_Str in Ruby
How to Preload Concerns in a Rails Initializer Using Rails 6/Zeitwerk
Generate All "Unique" Subsets of a Set (Not a Powerset)
How to Disable Wait Time for Watir
Are There Primitive Types in Ruby
Ruby Variable Name with Double Underscores
How to Write to File When Using Marshal::Dump in Ruby for Object Serialization
Travis Ci: Fatal: Role Does Not Exist
How to Upload a File with Watir and Ie