#map
í
Enumerable#map
First of all, what is Enumerable?
The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. I won't go further into what a mixin is, but you can think of it as a class which contains a combination of methods from other classes for now. If you understand loops and arrays and hashes, there's nothing new here. But you can do more with less lines of code, using the Enumerable mixin.
Take a look at this code:
It takes an array and multiplies each element with 10.
Now, #map is a method returning a copy of the its invoking collection. That means that not the actual array is modified, but instead you can assign #map's return to a new array. Here's how it looks like:
As you can see, arr hasn't changed! Instead, the modified values have been assigned to new_arr!
So #map is just some fancy fork of each! In fact, #map, and all the other Enumerable iterating methods are based off of each!
If you wanted to actually change arr, you could also use arr.map!{|a| a * 10} (notice the exclamation mark!).
First of all, what is Enumerable?
The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. I won't go further into what a mixin is, but you can think of it as a class which contains a combination of methods from other classes for now. If you understand loops and arrays and hashes, there's nothing new here. But you can do more with less lines of code, using the Enumerable mixin.
Take a look at this code:
- arr = [1, 2, 3, 4, 5]
- arr.each_index do |i|
- arr[i] *= 10
- end
- puts arr.join(", ") # => 10, 20, 30, 40, 50
Now, #map is a method returning a copy of the its invoking collection. That means that not the actual array is modified, but instead you can assign #map's return to a new array. Here's how it looks like:
- arr = [1, 2, 3, 4, 5]
- new_arr = arr.map { |x| x * 10 }
- puts arr.join(", ") # => 1, 2, 3, 4, 5
- puts new_arr.join(", ") # => 10, 20, 30, 40, 50
So #map is just some fancy fork of each! In fact, #map, and all the other Enumerable iterating methods are based off of each!
If you wanted to actually change arr, you could also use arr.map!{|a| a * 10} (notice the exclamation mark!).