Ruby Map
The Ruby library includes the module Enumerable. This library contains map(), reduce(), select(), and other functions.
Map This function of the Ruby Enumerable library is simple but profound. The map() method is applied to an array or a hash. The job of map() is to apply a function or block to each member of the array and return a new array. So, when you see
you read, for each number in [1,2,3,4,5] apply f(x) to return the array [f(1), f(2), f(3), f(4), f(5)]. In this case, the answer is [1,4,9,16,25]. One could encode it in traditional imperative programming as follows:
Using map, for example:
Or, you could encode it as follows:
[1,2,3,4,5] is the array. The function (or block) to be applied to each element is {|element| elementelement }. With the { } syntax, or the do-end syntax, the object in the vertical bars (represented by element) is the element of the array currently being acted upon by the block, and the last object in any function or block is the return value, so elementelement is returned. The net result is the following:
Suppose you wanted to provide data to a graphing program that plotted the square of the value.
In this case, each “point” is a tuple (array) with an element and its square. This returns the following:
The difference is that the block returns an array each time with the number and its square, so the result is an array of arrays. Since map returns an array, you can cascade map calls. For example, you could have a map block square each element, and then a second map block add 100. For example:
A number of the more complex operations can be solved by cascading with map calls.
comments powered by Disqus