Map vs collect

The ‘join block’ thread made me think about the difference between 'map’
and ‘collect’ (in terms of what I use them to mean, of course - they’re
synonymous in Ruby). In particular, if I were to implement a custom data
structure (a tree, e.g.), I’d have map return an isomorphic structure,
and collect to return something flattened out.

Which led to the following:

class Array
def collect(retval = [])
each {|i| retval << yield(i)}
retval
end
end

module Enumerable
def collect(retval = [])
each {|i| retval << yield(i)}
retval
end
end

p [1,2,3,4,5].collect("") {|i| “<<#{i}>>”}

It forks collect off from map, but is backward compatible if you don’t
supply an argument.

Also, if you want to collect something in your own object, with fancy
wrapping behaviour etc, you’d do it in your object’s << method, which
is arguably a better place for it than in Array/Enumerable.

martin