Ruby - Module Enumerable Module

Introduction

Hashes, Arrays, Ranges, and Sets all include a Ruby module called Enumerable.

Enumerable provides these data structures with a number of useful methods such as

  • include?, which returns true if a specific value is found;
  • min, which returns the smallest value;
  • max, which returns the largest; and
  • collect, which creates a new structure made up of values returned from a block.

In the following code, you can see some of these functions being used on an array:

Demo

x = (1..5).collect{ |i| i } 
p( x )                       #=> [1, 2, 3, 4, 5] 
#  ww  w.  j  a va2  s  .  co m
arr = [1,2,3,4,5] 
y = arr.collect{ |i| i } 
p( y )                       #=> [1, 2, 3, 4, 5] 
z = arr.collect{ |i| i * i } 
p( z )                       #=> [1, 4, 9, 16, 25] 

p( arr.include?( 3 ) )       #=> true 
p( arr.include?( 6 ) )       #=> false 
p( arr.min )                 #=> 1 
p( arr.max )                 #=> 5

Result

These same methods are available to other collection classes too, as long as those classes include Enumerable.

Here's an example using the Hash class:

Demo

h = {'one'=>'1', 
     'two'=>'2', 
     'three'=>'3', 
     'four'=>'4'}  

y = h.collect{ |i| i } #   w w  w.  j a  va2  s .  c o m
p( y ) 
p( h.min )    #=> ["one", "1"] 
p( h.max )    #=> ["two", "2"]

Result

Related Topic