What is Enumerable in Ruby?

Written by Supakorn Laohasongkram on August 7th, 2014

To enumerate means to mention one by one. Thus, enumerable means: is able to be counted or go through one after the other. And what class in Ruby could you enumerate over? (tick tock) Yes, array and hash. These are collection classes which are enumerable. It might be easy to assume that each method in Ruby is ONLY made for one particular super class. (For example, ".reverse", which could only be used with a string.) But this isn't necessary true for Enumerable. The Enumerable method works with enumerable classes; thus, it does not work only with array; but also with hash. Simply put: Enumerable in Ruby is a set of methods made specifically for enumerable classes like array and hash. And Ruby provides a host methods to manipulate these collection.

Let's look at one enumerable method of ".map" and apply them on both array and hash. To see how and if they actually work.

.map

Using with a hash
hash = {:age => 10, :height => 170, :year => 1988}
def map_hash(enumerable)
print enumerable.map { |key,value| value*10 } # => [100, 1700, 19880]
end
map_hash(hash) # => {:age=>10, :height=>170, :year=>1988}
Using with an array
array = [1,55,66,700,-3,0]
def map_array(enumerable)
print enumerable.map { |i| i*10 }
# => [10, 550, 660, 7000, -30, 0] end
map_array(array)
p array # => [1,55,66,700,-3,0]

What is the different between .each and .map?

One point that I should mention is the difference between the ".map" method and the ".each" method. They both could iterate over an array; however with one difference. ".map!" can manipulate the array or hash as it iterates over each element. While ".each" does not. Below is the example of a ".each" method and how ".each" left the original array exactly the same. (non-destructive.)

Using .each on an array
array = [1,55,66,700,-3,0]
def each(array)
array.each do |i|
p i*10 # => 10, 550, 660, 7000, -30, 0
end
end
each(array) # => [1, 55, 66, 700, -3, 0]
Using .map! on an array
array = [1,55,66,700,-3,0]
def map_array(array)
print array.map! { |i| i*10 }
# => [10, 550, 660, 7000, -30, 0] end
map_array(array)
p array # => [10, 550, 660, 7000, -30, 0]

As the last reminder, Enumerable in Ruby is a class which one could go through one after the other. And Ruby has offer us a wide variety of methods to manipulate these Enumerable classes. And don't forget the Enumerable methods are not only used for array! they can also be used for hash as well! I hope this article help you better understand this concept in some ways!

Thanks for reading!


© Copyright Supakorn Laohasongkram 2014