min_by method

The min_by method takes an enumerable collection and returns the item that qualifies as the "minimum", much the way min 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, min runs the block multiple times per item, as it compares various items to each other.

The magic of min_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]

# lowest number:
@numbers.min_by{|number| number}  #=> 0

# lowest number when negative:
@numbers.min_by{|number| 0 - number}  #=> 9

Pet Inventory

# pet with minimum quantity:
@inventory.min_by(&:quantity).name  #=> "rock"

# pet with fewest legs:
@inventory.min_by(&:legs).name  #=> "fish"

Pokey Things

# first pokey thing, alphabetically:
@pokey_things.min_by{|pokey_thing| pokey_thing}.chomp  #=> "cactus"

# smallest pokey thing by letter count:
@pokey_things.min_by(&:length).chomp  #=> "pole"

Heroku Log File

# heroku request with lowest response time:
@requests.min_by(&:response_time).id  #=> 8

# heroku request with lowest service time:
@requests.min_by(&:service).id  #=> 8

Leave a Reply

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