Ruby - Enumerable min max Custom Comparisons

Introduction

To make min and max to return items based on some other criterion, define the nature of the comparison inside a block.

You can similarly pass blocks to the max and min methods:

h.min{ |a,b| a[0].length <=> b[0].length }   
h.max{|a,b| a[0].length <=> b[0].length }   

So, if a hash contains items like this:

{'one'=>'1', 'two'=>'2'} 

then the two block arguments, a and b, would be initialized to two arrays:

a = ['one', '1'] 
b = ['two', '2'] 

Related Topic