Flowdock

Notes posted by masukomi

RSS feed
November 3, 2015 - (>= v1_9_2_180)
0 thanks

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