Thursday, September 29, 2011

Collect vs Map

Collect vs Map in ruby

I’ve been using collect in all my programs up till now, and I recently discovered that the map function is equivalent.

My question was what is the difference between them and which one is better to use. I investigated the net and found that it is a matter or convention more than a difference:
- collect is recommended to be used when the list is not changed:


ruby-1.8.7-p302 :009 > ["one", "two", "three"].collect{|item| item.length == 3}
=> [true, true, false]

- map is recommended to be used when the elements of the list have to be processed:

["one", "two", "three"].map{|item| process(item)}

No comments:

Post a Comment