Alexandru E. Ungur
1/12/2007 11:11:00 AM
>>> sender: "Robert Dober" date: "Fri, Jan 12, 2007 at 06:56:08PM +0900" <<<EOQ
> [..]
>
> The following is a very common pattern.
>
> an_enum.map{ |ele| ele.a_method }
>
> I believe that it is sufficiently common to be generalized.
>
> There are two idioms I would like to see
>
> an_enum.apply_to_all :a_method
Ok, I'm still a newbie, but why not extend map instead of introducing a
new method? As in:
%w[apples oranges kiwi].map :capitalize # => ["Apples", "Oranges", "Kiwi"]
Still feels like the good old "map" and acts like it...
Here's my naive implementation, that produced the result above:
class Array
alias :old_map :map
def map(arg = nil, &block)
if block
old_map &block
elsif ! arg.nil?
if arg.is_a?(Symbol)
old_map {|x| x.send(arg)}
else
raise ArgumentError, "Don't know how to handle #{arg.class} arguments"
end
else
raise ArgumentError, "No parameter and no block given!"
end
end
end
All the best,
Alex