.max_by

Finding the biggest in a hash


At The Flatiron School, we recently had an assignment called “Hashketball”, where we were iterating through hashes of players and stats. One assignment was to find the number of rebounds by the player with the biggest shoe size. Hmmmm… Tricky right? But maybe Ruby has some nifty functionality that can help us do this faster? And and so I came across .max_by

.max_by is very cool. It lets us sort through a hash and return the maximum value based on whatever criteria we give it. For example, to test this out I created the following hash:

test_hash = { “Justin” => { favorites: [“Jeff Koons”, “Matthew Barney”], least_favorites: [“Pop Art”]}, “John” => { favorites: [“St. Lucia”, “Bastille”], least_favorites: [“Indie”]} }

Using our nifty new .max_by, we can create a method that iterates through the hash (searching by name) and then gives us access to a key value pair. For example:

test_hash[name][:favorites].max_by { |x| x.length}

Will return “Matthew Barney” — the longest string from the values of the favorites: key. I have a feeling there are quite a few other cool ways we could be using max_by in our programs. Stay tuned as I learn more!

Email me when Justin Belmont publishes or recommends stories