Ruby - Module Mixin enumerable

Introduction

You can make your own class, implement an each method

Demo

class AllVowels 
  @@vowels = %w{a e i o u} # w  ww .j a va  2  s  .  c  o  m
  def each 
    @@vowels.each { |v| yield v } 
  end 
end 

x = AllVowels.new 
x.each { |v| puts v }

Result

AllVowels class contains a class array containing the vowels.

The enumerable module uses each method on the class that includes it.

The instance-level each method iterates through the class array @@vowels and yields to the code block supplied to each, passing in each vowel, using yield v.

Let's get Enumerable involved:

class AllVowels 
  include Enumerable 

  @@vowels = %w{a e i o u} 
  def each 
    @@vowels.each { |v| yield v } 
  end 
end 

x = AllVowels.new 
x.collect { |i| i + "x" } #["ax", "ex", "ix", "ox", "ux"] 
x.detect { |i| i > "j" } # "o" 
x.select { |i| i > "j" } # ["o", "u"] 
x.sort # ["a", "e", "i", "o", "u"] 
x.max # "u" 
x.min # "a" 

Related Topic