flat_map
![Wide documentation Importance_3](https://d2vfyqvduarcvs.cloudfront.net/images/importance_3.png?1349367920)
- 1_8_6_287
- 1_8_7_72
- 1_8_7_330
- 1_9_1_378
- 1_9_2_180 (0)
- 1_9_3_125 (0)
- 1_9_3_392 (0)
- 2_1_10 (38)
- 2_2_9 (0)
- 2_4_6 (0)
- 2_5_5 (0)
- 2_6_3 (0)
- What's this?
flat_map()
public
Returns a new array with the concatenated results of running block once for every element in enum.
If no block is given, an enumerator is returned instead.
[[1,2],[3,4]].flat_map {|i| i } #=> [1, 2, 3, 4]
![Default_avatar_30](https://www.gravatar.com/avatar/43e0398b89022d32b43de4c968069312?size=30&default=http://apidock.com/images/default_avatar_30.png)
![Default_avatar_30](https://www.gravatar.com/avatar/7e68a291a9a0ca27ac581aa1ef30f94d?size=30&default=http://apidock.com/images/default_avatar_30.png)
Re: close but no bananna
Actually, @tarasevich is right on this. Let’s have a look at your own example:
[["1","2"],["3","4"]].flat_map {|i| i[0] } # => ["1", "3"] [["1","2"],["3","4"]].map {|i| i[0] }.flatten # => ["1", "3"] [["1","2"],["3","4"]].flatten.map {|i| i[0] } # => ["1", "2", "3", "4"]
You are right that both #map and #flatten are non-commutative, it does matter which method is called first.
But #flat_map is equivalent to mapping first and then concatenating (flatten) the results, even if the name might suggest the opposite.
To correctly interpret the method name, you should think of it mathematically as a function composition.
![Default_avatar_30](https://www.gravatar.com/avatar/815c3e81d0519ba50d579c79c1bfb4de?size=30&default=http://apidock.com/images/default_avatar_30.png)
Not exactly like map {}.flatten
To clarify on the last comment, conceptually it’s the same, but #flat_map will perform better because there is no need to create an intermediate Array
![Default_avatar_30](https://www.gravatar.com/avatar/de523f5b29624576b077ef7649249f39?size=30&default=http://apidock.com/images/default_avatar_30.png)
Not exactly like map {}.flatten
To also give dimension, is about 4.5 times faster then map {}.flatten.
![Default_avatar_30](https://www.gravatar.com/avatar/b8ef358eccf3bddaea19a242f6b14c40?size=30&default=http://apidock.com/images/default_avatar_30.png)
close but no bananna
@tarasevich noted that
a.flat_map(&b) works exactly like a.map(&b).flatten!(1)
This is backwards because map and flatten are not always interchangeable in order. Mapping over the example array only gives you 2 items. This can result in significant differences depending on what you’re doing in the map. This is easier to demonstrate if we change the example to strings.
[["1","2"],["3","4"]].map {|i| i[0] } # => ["1", "3"] [["1","2"],["3","4"]].map {|i| i[0] }.flatten # => ["1", "3"]
BUT if you swap the order
[["1","2"],["3","4"]].flatten.map {|i| i[0] } # => ["1", "2", "3", "4"]
in order to remember what it is equivalent to just note that the method name is already in the correct order. flat_map -> flatten + map