max_by method

The max_by method takes an enumerable collection and returns the item that qualifies as the "maximum", much the way max does. The main difference is that it's much more efficient for complex comparisons. You must specify a block, and it will only be run once for each item in the collection. By contrast, max runs the block multiple times per item, as it compares various items to each other.

The magic of max_by is that it stores the return value of the given block for each item in the collection, then does all the comparison sorting on those return values directly.

Number List

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

# highest number:
@numbers.max_by{|number| number}  #=> 9

# highest number when negative:
@numbers.max_by{|number| 0 - number}  #=> 0

Pet Inventory

# pet with highest quantity:
@inventory.max_by(&:quantity).name  #=> "beetle"

# pet with most legs:
@inventory.max_by(&:legs).name  #=> "scorpion"

Pokey Things

# last pokey thing, alphabetically:
@pokey_things.max_by{|pokey_thing| pokey_thing}.chomp  #=> "pole"

# largest pokey thing by letter count:
puts @pokey_things.max_by(&:length).chomp
    #=> "cactus holding poles with knives attached"

Heroku Log File

# heroku request with highest response time:
@requests.max_by(&:response_time).id  #=> 2

# heroku request with highest service time:
@requests.max_by(&:service).id  #=> 

Leave a Reply

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