Ruby - Build your own collection class out of Enumerable

Introduction

You can create your own collection class via Enumerable to get methods such as max, min, and collect.

You can do that by including the Enumerable module in your class and then writing an iterator method called each like this:

class MyCollection  
   include Enumerable 

   def initialize( someItems ) 
     @items = someItems 
   end 

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

Here you initialize a MyCollection object with an array, which will be stored in the instance variable, @items.

When you call one of the methods provided by the Enumerable module (such as min, max, or collect), this will call the each method to obtain each piece of data one at a time.

Here the each method passes each value from the @items array into the block where that item is assigned to the block parameter i.

Now you can use the Enumerable methods with your MyCollection objects:

Demo

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

   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 } )

Result

Related Topic