Map
So, you have an array, a mutable object, and you want to output a change each and everyone of it's contents accordingly without really changing the it's value. You could use a for loop, but it's too long, or you could use the each method but it's what you've been using and repetitive use isn't good. You need something concise and efficient, you should use the map method.
How does it work?
The map method, is not similar to the function with the same name that appears in python, or js. Unlike map in the mentioned languages, map in ruby doesn't call a function on an enumerable, it is more like an advanced version of each. There is another method that is exactly the same as map, called collect, in ruby. The only difference between them is popularity.
Okay, but still why don't I just use each I don't really see the difference?
The answer is simple. Each doesn't return the changed value.
What?
Yeah, if you want to see the value it must be assigned to a different variable or reassigned to the same one, other wise there is no output change. With map you can just return the value without permanently changing or reassigning a value. That's why it's used more than each. Also, readability in ruby is one part of its benefits and frankly, the syntax of map is just as readable as each but due to its differences the additional things needed to do the same thing make each, overall, a poorer choice in most cases over map. Here's an example.
So what should I be using now?
IMHO, it all comes down to opinion, but I do suggest that using map instead of each would probably be a better option.
Later
Hope you liked the post. Bye. :)
Top comments (2)
You can also use Array#map! to replace the values within the array with the return value.
True, I probably should have mentioned that as well.