minmax method

The minmax method takes an enumerable collection and returns a 2-element array consisting of the minimum and maximum values, as compared via the sort method. You pass a block to the method which is used in element comparisons. See the examples below for the syntax.

Number List

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

# lowest/highest numbers:
@numbers.minmax  #=> [0, 9]

# lowest/highest numbers when negative:
@numbers.minmax{|a,b| 0 - a <=> 0 - b}  #=> [9, 0]

Pet Inventory

# pets with minimum/maximum quantity:
@inventory.minmax.map(&:name).join(', ')  #=> ["rock", "beetle"]

# pets with fewest/most legs:
@inventory.minmax{|a,b| a.legs <=> b.legs}.map(&:name).join(', ')  #=> ["fish", "scorpion"]

Pokey Things

# first/last pokey things, alphabetically:
@pokey_things.seek(0)
@pokey_things.minmax.map(&:chomp).join(', ')  #=> ["cactus", "pole"]

# smallest/largest pokey things by letter count:
@pokey_things.seek(0)
@pokey_things.minmax{|a,b| a.length <=> b.length}.map(&:chomp).join(', ')  #=> ["pole", "cactus holding poles with knives attached"]

Heroku Log File

# heroku requests with lowest/highest response times:
@requests.minmax.map(&:id)  #=> [2, 31]

# heroku requests with lowest/highest service times:
@requests.minmax{|a,b| a.service <=> b.service}.map(&:id)  #=> [8, 2]

Leave a Reply

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