From: Robert Dober Date: 2008-12-05T01:28:40+09:00 Subject: Re: Enumerable#select used to return actual values On Thu, Dec 4, 2008 at 5:07 PM, Yukihiro Matsumoto wrote: > Hi, > > In message "Re: Enumerable#select used to return actual values" > on Fri, 5 Dec 2008 00:47:45 +0900, Trans writes: > > |> (1..10).collect{ |a| a * a if a > 5 }.compact > |> > |> The only time this doesn't work is when you want to preserve nils in > |> your original array. > | > |And that's exactly what I suggested for #compact, to take a block but > |faster b/c it's one pass. > > I don't deny the existence of use case of such method (although I > cannot think of any realistic one right now), but its name should not > be #compact, since it does far more than compacting the receiver. > > matz. > > Hmmm just a little brainstorming on this [1, nil, false].compact --> [1] [1, nil, false].compact_by{ |x| x.nil?} --> [1, false] o = Object::new a.collect{ |x| some_condition(x) ? x : o}.compact_by{ |x| x==o} But actually the implementation is *easy* ;) module Enumerable alias_method :compact_by, :reject ### ;) end However what about module Enumerable alias_method :__old_reject__, :reject def reject( *args, &blk ) raise SomeDescriptiveError unless blk.nil? || args.empty? return __old_reject__( &blk ) if blk __old_reject__{ |x| args.include? x } end end I guess I might put this into Labrador ;) Cheers Robert or -- Ne baisse jamais la tête, tu ne verrais plus les étoiles. Robert Dober ;)