Map vs Collect, and Other Ruby Synonyms

Ruby has a ton of high-level iterators. So how are you supposed to know which one to use when? More specifically, what’s the difference between map and collect? They each produce a new array containing the results of the block applied to each element of the receiver. Both map! and collect! are offered to modify the array in place.

Some sources assert that the two methods are the same. Both are array methods that can work with anything that is Enumerable. Ruby is written in C, and the C-level implementation is identical. Here is that implementation:

image

But then why have both? 

Wikipedia explains that Ruby provides both to make programmers feel more comfortable. Map is provided by many programming languages, and collect came from a language called Smalltalk

Other Ruby synonyms include the shovel operator << and concat. The shovel is different than += because += creates a new String in memory, but << is faster because it just modifies the original one

The for loop vs each appear to be synonyms but there is a scoping difference. The local variable used in for loops still exists after the loop, which might have some unintended consequences for your program.

image

On a different note, .size is an alias for .length. But count, which seems similar, is actually different

image

When the inventor of Ruby, Matz himself, was asked to explain why he provides so many ways to do the same thing, he said:

Ruby inherited the Perl philosophy of having more than one way to do the same thing. I inherited that philosophy from Larry Wall, who is my hero actually. I want to make Ruby users free. I want to give them the freedom to choose. People are different. People choose different criteria. But if there is a better way among many alternatives, I want to encourage that way by making it comfortable. So that’s what I’ve tried to do. Maybe Python code is a bit more readable. Everyone can write the same style of Python code, so it can be easier to read, maybe. But the difference from one person to the next is so big, providing only one way is little help even if you’re using Python, I think. I’d rather provide many ways if it’s possible, but encourage or guide users to choose a better way if it’s possible.

So that’s the answer. When presented with two or three or twelve different ways to do the same thing in Ruby, you should choose whichever way makes you the most comfortable.