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?
There’s no difference, in fact
mapis implemented in C asrb_ary_collectandenum_collect(eg. there is a difference betweenmapon an array and on any other enum, but no difference betweenmapandcollect).Why do both
mapandcollectexist in Ruby? Themapfunction 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
eachmethod).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
eachbut can only use simple pointer manipulation which is significantly faster.Similar optimizations exist for a number of Array methods like
ziporcount.