0044 Flat

Flatten your arrays!

The flat_map defined in Enumerable does 2 things:

  • It transforms data like map.
  • « flattens » the result of each transformation by one level if it is an array.

Just as map has an alias collect, flat_map has an alias collect_concat!

0044-flat_1.png

flatten is defined for Array and Hash and does just one thing: it « flattens » arrays, but the depth is configurable. For Array, the default depth is illimited, for Hash, it’s 1! A negative value indicates illimited depth.

0044-flat_2.png

The use of one or the other will depend on the context. However, the common case concerns 1 level, and then flat_map is on average 2 times more efficient than map { ... }.flatten.

Links to Ruby documentation for flat_map, Hash#flatten and Array#flatten.