tags:

views:

90

answers:

3

Whenever I see Ruby code that says:

arrayNames.collect { ... }

I forget what collect is and have to look up what it is, and find that it is the same as map().

Map, I can understand, mapping 1 byte to a pixel, and function is to map an x to a y, a 2 to a 4, a 5 to a 25, etc. But where does the name "collect" come from? Maybe that will help to remember what a "collect" method is.

+5  A: 

It comes from Smalltalk old days. Smalltalk used collect and select instead of map and filter (as used in many other languages) for iterating on its collections.

kriss
hm... and talking about Ruby not having a `filter` method...
動靜能量
and Perl uses `grep` instead of `filter`, but you get the idea.
kriss
Thanks for the insight. Well I can't say I found any of them unintuitive or hard to remember, just was slightly confused which variant is more idiomatic?I do prefer 'map' (shorter, more familiar) - but are both of them here to stay, used just as well by gurus?
inger
thanks for kriss nice answer. i was reading The Ruby Programming Language book by O'Reilly and it was using `collect` on one page and `map` on another... maybe the gurus want to test our limits
動靜能量
maybe the real question is why Ruby author chose to give two names to the same method. I guess it's probably to make things easier...
kriss
+3  A: 

kriss is right that the method name has its origins in Smalltalk but to help remember what it does when you see it used you can think of it as "collecting the results from the block in a new array".

mikej
When it is Array.sort, Array.shuffle, Array.uniq, I also would think of collecting the results too. On the other hand, if thinking of "collection", then it may be related to math's set concept.
動靜能量
+3  A: 

To add to the other answers, it is kind of an inside-joke in Smalltalk:

  • inject:into:
  • collect:
  • select:
  • reject:
  • detect:

Spot the pattern?

Jörg W Mittag
so does smalltalk have "inspect" too?
動靜能量
@Jian Lin: In Smalltalk, the graphical IDE, the IDE, the text editor, the language, the application and the compiler are all one and the same. Therefore, it doesn't have an `inspect` method like Ruby has, but instead an `Inspector` window that allows you to inspect arbitrary objects. The `...ect` methods are all collection methods.
Jörg W Mittag
This is made the official answer since it gave a reason why the word `collect` might be used instead of `map` and a good memory device to remember the strange one `collect` is indeed `map`.
動靜能量