Notes posted by WhyEee
RSS feed
WhyEee -
November 3, 2015
1 thank
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.