liveBook · Manning

Map!

As explained in The Well-Grounded Rubyist, Fourth Edition

map! is a mutating collection method that replaces each element with the value produced by applying a transformation block.

Use `map!` when you want to transform a collection’s elements in place. Unlike `map`, which builds a new array of block results, `map!` replaces the elements in its receiver. It is also called `collect!`. section 10.6.1 section 10.6.2

Uppercase an existing array

`names = %w(David Yukihiro Chad Amy)` followed by `names.map!(&:upcase)` changes the `names` array itself. Use `names.map { |name| name.upcase }` instead when you want a new array of uppercase names. section 10.6.2 section 10.6

The block’s result matters, not merely what the block does along the way. A block ending in `puts` returns `nil`; with `map`, that produces an array of `nil` values. `map!` uses block results as replacements, so choose a block that returns the values you want to keep. section 10.6.1 section 10.6.2

`Array#map!` belongs to `Array`, not `Enumerable`: a general `map` can return an array even when its receiver is another kind of enumerable, but in-place mapping requires a suitable receiver. Sets also provide `map!`. section 10.6.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines in-place mapping and contrasts its receiver types with map, without detailing map!’s implementation or return value.
Examples
Shows an array of names changed in place with `names.map!(&:upcase)`.
What it assumes
Assumes familiarity with Ruby arrays and blocks, then distinguishes in-place mapping from map’s new-array result.
What you can do after
Apply it via Ruby’s Array#map! or Set#map! when the collection itself should change.
How it connects
Connects map! to map, collect!, Enumerable, arrays, sets, and block return values.

Also explained in

Compare how 2 books explain map! →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.