Arrays, Hashes, Ranges in Ruby are called collection classes. If a class is a collection then you would expect them to do various things such as: traverse, sort etc.

What if you are writing your own class and want to give that class the same functionality of a hash or an array. By mixin the module Enumerable this could easily be achieved.

By writing an iterator called each, you can have your class do functions such as: map, include? and find_all?.

If the objects in your collection implement meaningful ordering using the <=> method, you can also use methods such as min, max and sort.

Let’s give an example:

You write a Ruby class called FindWovels which accepts a string as its argument at initialization.

Then you write an each method. This method scans the string using Regular Expressions and brings you the vowels.

It is now upto you on how to utilize the each method.

    
class FindVowels
    include Enumerable
    def initialize(string)
        @string = string
    end
    
    def each
        @string.scan(/[aeiou]/) do |vowel| yield vowel
        end
    end
end

vowel = FindVowels.new("abcdefg")

vowel.each do |x|
    puts x
end

# [a,e]

enumerable#map Method

Returns a new array with the results of running block once for every element in enum.

If no block is given, an enumerator is returned instead.

map { |obj| block } → array

If we use the map method on our previous example and print the array, you will see that it is modified…

    
arr = vowel.map { |i| i + "s" }

arr.each do |s|
    puts s
end

# [as,es]

Rest of the public methods

There are bunch of other public methods related to Enumerable module and here they are:

IF YOU LIKED IT THEN SHARE IT