I have Googled this and got patchy / contradictory opinions – is there actually any difference between doing a map
and doing a collect
on an array in Ruby/Rails?
The docs don't seem to suggest any, but are there perhaps differences in method or performance?
Best Answer
There's no difference, in fact
map
is implemented in C asrb_ary_collect
andenum_collect
(eg. there is a difference betweenmap
on an array and on any other enum, but no difference betweenmap
andcollect
).Why do both
map
andcollect
exist in Ruby? Themap
function has many naming conventions in different languages. Wikipedia provides an overview:Ruby provides an alias for programmers from the Smalltalk world to feel more at home.
Why is there a different implementation for arrays and enums? An enum is a generalized iteration structure, which means that there is no way in which Ruby can predict what the next element can be (you can define infinite enums, see Prime for an example). Therefore it must call a function to get each successive element (typically this will be the
each
method).Arrays are the most common collection so it is reasonable to optimize their performance. Since Ruby knows a lot about how arrays work it doesn't have to call
each
but can only use simple pointer manipulation which is significantly faster.Similar optimizations exist for a number of Array methods like
zip
orcount
.