Ruby comes equipped with some very useful built-in methods. Though you can always write your own, it's helpful to know some of the basic methods, since your own method might use other built in methods. It's also important to know how to look up methods and what they are capable of. Personally, I'm a big fan of Ruby Docs.
This blog post will just focus on one such method: the .map method. The map method is an enumerable method, which means that it passes the block of code to every element of the object array.
Let's take a look at a couple of examples of why this might be useful.
Let's say I have an array of numbers 1 through 5 and I wanted to make a new array with their square products. I can use .map to achieve this quite easily.
The .map is passing the block of code in the curly brackets to the object array. Each object i is being multiplied by its own value and then stored in the new array called sq array.
Note that the changed array was stored in a new array called sq_array to be accessed later. Map is not destructive in that it does not permanently change the values of array. That's why when we call array again the values are the original values. .map! however, can be used destructively to overwrite the values of the original array.
Let's look at one more example of how this might be useful. Let's say I had an array of names but they were all accidentally written in upper case. Using our handy little map trick and a couple other built in ruby methods we can fix that.
This time the block of code passed via the map method to the friends array contained the method downcase, which changed all the letters to lowercase, and the capitalize, which capitalized the first letter.
And remember, for more examples you can always try stack overflow or ruby docs.
Coming Soon!