Ruby - Add custom min and max for your own collection class

Introduction

Consider the following code

class MyCollection  
   include Enumerable 

   def initialize( someItems ) 
     @items = someItems 
   end 

   def each 
     @items.each{ |i|  
       yield( i ) 
     } 
   end 
end 

things = MyCollection.new(['x','yz','d','ij','java']) 

p( things.min )        
p( things.max )        
p( things.collect{ |i| i.upcase } ) 

Currently the min and max methods adopt the default behavior from Enumerable:

  • They perform comparisons based on numerical values.

To provide custom min and max methods.

Demo

class MyCollection  
  include Enumerable # from w  ww . j a  va 2  s  . co m

    def initialize( someItems ) 
        @items = someItems 
    end 
                         
    def each 
        @items.each{ |i| yield i } 
    end 
                         
    def min     
        @items.to_a.min{|a,b| a.length <=> b.length } 
    end 

    def max          
        @items.to_a.max{|a,b| a.length <=> b.length } 
    end 
end 

things = MyCollection.new(['z','xy','d','Java','xml','Javascript']) 
x = things.collect{ |i| i }  
p( x ) 
y = things.max 
p( y ) 
z = things.min 
p( z )

Result

Related Topic