Ennumerability

Enumera-what???

12/10/2014

So by this point we have pretty much established that Ruby is pretty awesome. The kind of girl you can bring home to Mom. She has all these great traits that you look for in a (programming) girl. She is easy to understand. Functional. And has class(es). Ok, joking aside, the language is sweet. One of the super cool things it can do is have collections. Also known as arrays and hashes (if you already forgot, take a look here). But let's be honest with ourselves, most programming languages have those in one form or another. What makes Ruby so special is something called the enumerable module. I know that sounds tricky, but by the time I'm done, I hope to have you understanding way more.

So the enumerable module is a fancy way of saying that it has lots of iteration methods. "What is an iteration method," you ask. Let me show you. The .each method is the most basic example.


              array = [1,2,3,4,5]
              array.each |i| do 
                puts i
              end

              1
              2
              3
              4
              5

            
Basically what it does is for each i (this can be anything, it just represents an item in the array) do something. In this case, it was puts that item to the screen. Pretty neat right? Well, the enumerable module adds way more methods that are capable of far more. Today, I want to focus on the method .map.

The .map method is going to allow you to take in a collection, modify it, then return a new array based on that method. Let's take a look using the same array as before:


              array.map { |x| x + 5 }
              
              [6,7,8,9,10]
            
As you can see, .map took each element of the array, multiplied it by itself, then printed a new array for us. This can be very useful when you are trying to manipulate a large set of data. You can even store the results in a variable for later use.

Hope this helped with your understanding of enumerables!