From: Daniel Berger Date: 2006-06-30T20:51:39+09:00 Subject: Re: Symbol#to_proc is just so beautiful Omer Raviv wrote: > Berger, Daniel wrote: > > >> There must be a way to ditch that '&' somehow. I'd prefer this: >> >> [1,2,3].all?(:positive?) >> > > > What you are suggesting is basically an expansion of something that was > suggested in RCR50 and rejected. > (http://www.rcrchive.net/rejected.html#rcr50) > Heh, I'd forgotten it was ever suggested before. > I like the idea too. It would be even better if you could also pass > parameters along. > > Here are a few more examples: > > [1,2,3].any?(:>, 4) > > [1,2,3].map(:*, 4) #-> [4,8,12] > > people.collect(:name) > > people.select(:retired?) > > people.sort_by(:age) > > favorite_numbers.select(:between?, 100,200) > > people.each(:give_compensation, 50) > > > Here's the implementation: > Here's my implementation for Array#map. class Array def map(*args) array = [] hash = {} current = nil args.each{ |arg| if arg.is_a?(Symbol) hash[arg] = [] current = arg else hash[current] << arg end } self.each{ |e| hash.each{ |m, params| unless params.empty? e = e.send(m, *params) else e = e.send(m) end } yield e if block_given? array << e } array end end (Logan Capaldo refactored this somewhat) > Now, I need help. As you may notice - the above only extends Array. If > you change "class Array" to "module Enumerable" in the above code, it > turns out that Ruby (1.8.4) refuses to let you override methods such as > map, while at the same time, "any?" and "all?" work fine. Anyone got a > clue as to how I could fix this? > Array#map is overridden in array.c, so modifying it in Enumerable won't affect Array. Regards, Dan