DEV Community

Cover image for How to use the Ruby minmax_by Method

Posted on • Updated on

How to use the Ruby minmax_by Method


Hey, if you're a beginner in ruby or a senior developer, the minmax_by method is probably going to save you some time and thinking.

Its uses are...?

Well, since you asked, its uses are pretty much straight forward. It returns the smallest and largest value in an iterable corresponding to the condition in the given block; without a block it returns an enumerator. So, it's used for strings, arrays, hash keys, etc., but its best use is making the lines and lines of code you may have written using the max() and min() methods utter trash! Trash


The syntax for this method is quite simple and you're probably thinking
Probably not
but it's true.
Without a block it looks like this:

With a block you can do things like this:

P.S. Creativity is Key

Be creative in your use of the method, it really helps.

When to use it?

Not everyone, especially beginners, know when and why a specific method or function is a better option than what they're currently using. Questions like, why use map instead of each or the standard for statement, why puts instead of print, or why minmax_by instead of our old buddies max() and min(). The answer is simple, what do you need? If you're looking to get the maximum and minimum values from an iterable under specific circumstances, then yeah, minmax_by is your guy(unintended rhyme); if not then your more likely options are max() or min(), maybe even minmax (I know, another one). Like I said, creativity really helps. Be creative in your thought process, it'll make you proficient in ruby.


Brain Power Picture: Floating Dude
Knowledge, or as I like to say #Knowledge, is the only thing standing in the way of you and creativity. You need creativity, so learn other ways to apply the minmax_by method.

It's the End of the World !

It's the end of the world as we know it!
If you got all the way to the end that's great. If you skipped some parts, that's alright as well.

Top comments (0)