The map method for enumerables is so awesome. I promise. Check it out. You have an array like this:


my_array = [1, 2, 3, 4]

Standard array, right? Nothing special about the numbers inside it. Let's apply a little map magic to it:


super_sweet_array = my_array.map { |i| "Super sweet!"}

Check out our new array!


  {"Super sweet!", "Super sweet!", "Super sweet!", "Super sweet!"}

Well, that's pretty awesome. But what exactly happened here? When we call map on an array, we're telling it to iterate through each item of the array, which we're calling i, and then perform the "block" that is included in the brackets, and then return the values in a new array. In this case, our block simply said to turn i into "Super sweet!"- but we can probably get crazier. Should we? Of course, we should!


double_the_fun_array = my_array.map { |i| i * 2 }

And that gets us....

[2, 4, 6, 8]

Woot! Easy doublification! Just like that! Can you imaging if you had an array of 30 numbers, and you needed to double them all? Of course, you could always write your little while loop, but it would be much more efficient to use the map method as we just did. Now, how about we go crazy extreme:


  what_in_the_world_array  = my_array.map { |i| (i == 1 ? "what" : i == 2 ? "in" : i == 3 ? "the" : i == 4 ? "world" : i)}

By throwing in a few, albeit complicated, ternary notations, suddenly our standard array turns into:


["what", "in", "the", "world"]

When would you ever need to use something like this example? Probably never, but you can use something similar if you need to replace a particular value of an element in your array. Say, if you need to change all of your "10:30"s in an array to "11:30"s because your daily schedule has been changed, you can set up a nifty { |i| i == "10:30" ? "11:30" : i } in your block and presto, all of your "10:30"s are now "11:30"s!

Seriously, the map method is just too cool. And if you don't agree, then DEATH BEES FOR YOU!


  DEATH_BEES_FOR_EVERYONE = my_array.map { |i| i < 4 ? "DEATH BEES!" : "DEATH BEES FOR EVERYONE!!!!"}
  

Well, look at that. I did find a use for it.