The max method takes an enumerable collection and returns the item that qualifies as the "maximum". For numbers, this is pretty straightforward, and you don't even need to provide any arguments for simple applications. For other objects, however, it's usually necessary to specify a block that will be used to sort the items by whatever criteria you specify.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
- Practice this method as an interactive kata on Codewars!
Numer List
@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] # highest number: @numbers.max #=> 9 # highest number when negative: @numbers.max{|a,b| 0 - a <=> 0 - b} #=> 0
Pet Inventory
# pet with highest quantity: @inventory.max.name #=> "beetle" # pet with most legs: @inventory.max{|a,b| a.legs <=> b.legs}.name #=> "scorpion"
Pokey Things
# last pokey thing, alphabetically: @pokey_things.seek(0) @pokey_things.max.chomp #=> "pole" # largest pokey thing by letter count: @pokey_things.seek(0) @pokey_things.max{|a,b| a.length <=> b.length}.chomp #=> "cactus holing poles with knives attached"
Heroku Log File
# "heroku request with highest total response time: @requests.max.id #=> 31 # heroku request with highest service time: @requests.max{|a,b| a.service <=> b.service}.id #=> 2