Ruby map, collect and select
As a newcomer to Ruby, I have often been confused by the 3 very similar enumerators on the Array class: map, collect and select. Let’s try to figure this out using an example.
All three methods have a similar signature and take a block parameter. The map and collect methods both return an array of values returned by the block. The select method will return the actual values being iterated over if the block evaluates to true. Here it is important to know that any Ruby object can be evaluated as a boolean. (Pretty much every object will evaluate to true except nil and false)
The previous example doesn’t really show how we would use map or collect – let’s try another example.
Here the map method makes a bit more sense. So what’s the difference between the map and collect methods? Turns out, there is no difference. In fact, if you look at the Ruby Documentation you will see that under the hood both map and collect are implemented as the C rb_ary_collect method.
Happy coding.