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:
- #all?
- #any?
- #chunk
- #collect
- #collect_concat
- #count
- #cycle
- #detect
- #drop
- #drop_while
- #each_cons
- #each_entry
- #each_slice
- #each_with_index
- #each_with_object
- #entries
- #find
- #find_all
- #find_index
- #first
- #flat_map
- #grep
- #group_by
- #include?
- #inject
- #lazy
- #map
- #max
- #max_by
- #member?
- #min
- #min_by
- #minmax
- #minmax_by
- #none?
- #one?
- #partition
- #reduce
- #reject
- #reverse_each
- #select
- #slice_after
- #slice_before
- #slice_when
- #sort
- #sort_by
- #take
- #take_while
- #to_a
- #to_h
- #zip