concept map in category ruby

appears as: map
The Well-Grounded Rubyist, Third Edition

This is an excerpt from Manning's book The Well-Grounded Rubyist, Third Edition.

The syntax &: is an abbreviated way of iterating over each of the elements in the tickets array and selecting the largest number. &: is often used with the map method, iterating over each element in an array, hash, or range and applying a method:

At this point, we’ve looked at examples of each methods and how they link up to a number of methods that are built on top of them. It’s time now to look at some methods that are similar to each but a little more specialized. The most important of these is map. In fact, map is important enough that we’ll look at it separately in its own section. First, let’s discuss some other each relatives.

10.6.1. The return value of map

The return value of map, and the usefulness of that return value, is what distinguishes map from each. The return value of each doesn’t matter. You’ll almost never see this:

On the other hand, map returns a new object: a mapping of the original object to a new object. So you’ll often see—and do—things like this:

result = array.map {|x| # code here... }

The difference between map and each is a good reminder that each exists purely for the side effects from the execution of the block. The value returned by the block each time through is discarded. That’s why each returns its receiver; it doesn’t have anything else to return, because it hasn’t saved anything. map, on the other hand, maintains an accumulator array of the results from the block.

This doesn’t mean that map is better or more useful than each. It means they’re different in some important ways. But the semantics of map do mean that you have to be careful about the side effects that make each useful. Side effects are an important concept that’s covered extensively in chapter 16. In the meantime, an example will help you use map more effectively.