max method

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.

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:  #=> "beetle"

# pet with most legs:
@inventory.max{|a,b| a.legs <=> b.legs}.name  #=> "scorpion"

Pokey Things

# last pokey thing, alphabetically:
@pokey_things.max.chomp  #=> "pole"

# largest pokey thing by letter count:
@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:  #=> 31

# heroku request with highest service time:
@requests.max{|a,b| a.service <=> b.service}.id  #=> 2

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>