Ruby Enumerables

Background

When we talk about Ruby Enumerables, most folks directly jump into .map, .select, .each , .find etc. methods that can be called on collections (like arrays, hashes). That said, it is important to understand that there is a difference between “Enumerator” and “Enumerable”. Enumerator as the english word means is “get the count of” or “number the collection”. In Ruby “enumerable” is a module that is used as a mixin. Array.each returns an enumerator and it is the classe’s job to implement .each and return an enumerator. The enumerable methods act on that enumerator to provide meaningful methods like sorting, searching, filtering etc.

The Ruby official documentation on modules says this:

The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection. If Enumerable#max, #min, or #sort is used, the objects in the collection must also implement a meaningful <=> operator, as these methods rely on an ordering between members of the collection

Examples

The entire enumerables module is documented here

Most of them are self explanatory and here is some sample code

Another Example

Explanation

If we look at the html source for the summer dresses products, we see a pattern i.e. there are blocks of divs that are defined by class: “product-container”. Inside each such div, there is a pattern of divs again, where the child div(class:”right-block”) contains the product text and the child div(class: “content_price”) contains the product price. We identify “that” product-container that contains the child div(class: “right-block”) and then its child and so on, which has an achor <a> that can be identified using the “text” we pass as parameter. Once we retrieve “product-container”, we step through its html tree to retrieve the product price. Now we get the product price for the product whose text is the parameter we pass in.

enumerable

 

Closing Thoughts

Ruby Enumerables are very powerful and there are many methods defined the Enumerable module. Reading the Ruby docs itself is sufficient and practicing them would give a good idea further.