The minmax_by method takes an enumerable collection and returns a 2-element array consisting of the minimum and maximum values, as calculated via the given block. See the examples below for the syntax.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
- Practice this method as an interactive kata on Codewars!
Number List
@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] # lowest/highest numbers: @numbers.minmax_by{|number| number} #=> [0, 9] # lowest/highest numbers when negative: @numbers.minmax_by{|number| 0 - number} #=> [9, 0]
Pet Inventory
# pets with minimum/maximum quantity: @inventory.minmax_by(&:quantity).map(&:name).join(', ') #=> ["rock", "beetle"] # pets with fewest/most legs: @inventory.minmax_by(&:legs).map(&:name).join(', ') #=> ["fish", "scorpion"]
Pokey Things
# first/last pokey things, alphabetically: @pokey_things.seek(0) @pokey_things.minmax_by{|thing| thing}.map(&:chomp).join(', ') #=> ["cactus", "pole"] # smallest/largest pokey things by letter count: @pokey_things.seek(0) @pokey_things.minmax_by(&:length).map(&:chomp).join(', ') #=> ["pole", "cactus holding poles with knives attached"]
Heroku Log File
# heroku requests with lowest/highest response times: @requests.minmax_by(&:response_time).map(&:id) #=> [8, 2] # heroku requests with lowest/highest service times: @requests.minmax_by{|request| request.service}.map(&:id) #=> [8, 2]