min method

The min method takes an enumerable collection and returns the item that qualifies as the "minimum". 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.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# lowest number:
@numbers.min  #=> 0

# lowest number when negative:
@numbers.min{|a,b| 0 - a <=> 0 - b}  #=> 9

Pet Inventory

# pet with minimum quantity:
@inventory.min.name  #=> "rock"

# pet with fewest legs:
@inventory.min{|a,b| a.legs <=> b.legs}.name  #=> "fish"

Pokey Things

# first pokey thing, alphabetically:
@pokey_things.min.chomp  #=> "cactus"

# smallest pokey thing by letter count:
@pokey_things.min{|a,b| a.length <=> b.length}.chomp  #=> "pole"

Heroku Log File

# heroku request with lowest response time:
@requests.min.id  #=> 1

# heroku request with lowest service time:
@requests.min{|a,b| a.service <=> b.service}.id  #=> 8

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>