From: Robert Klemme Date: 2005-07-12T18:50:50+09:00 Subject: Re: accessing index inside map Brian Candler wrote: > On Tue, Jul 12, 2005 at 10:04:02AM +0100, Brian Candler wrote: >> module Enumerable >> def altmap(meth=:each) >> res = [] >> send(meth) { |*args| res << yield(*args) } >> res >> end >> end > > P.S. I note that some Enumerable methods already take arguments: > detect/find, grep, inject could have meth=:each as a later argument > for backwards-compatibility. > > The only awkward ones are to_set and zip. Even then, they could be > made backwards-compatible by checking if the first argument is a > Symbol and using it as a method name in that case. > > I don't really see the usefulness of the foo.to_set(klass,*args) > syntax anyway, given that it just calls klass.new(foo,*args). > However, I can see uses for > h.to_set(:each_key) > h.to_set(:each_value) IMHO the enumerator approach is slightly superior as your suggestion can lead to conflicts with current method arguments as you have noticed. Personally I don't have a problem using a.to_enum(:each_with_index).inject(0) {|sum,(a,i)| sum + a*i} I think this is more flexible and modularized. And the overhead of a new instance creation is usually neglectible compared to the iteration overhead. Kind regards robert