Hi --

On Sun, 30 Nov 2008, Robert Dober wrote:

> On Sun, Nov 30, 2008 at 8:54 AM, Robert Klemme
> <shortcutter / googlemail.com> wrote:
>> On 30.11.2008 04:46, Mike Austin wrote:
>>>
>>> I'm pretty sure select used to use the actual value of the called block,
>>> instead of treating it as just a truthy/falsey boolean.
>>
>> I am pretty sure it did never.  Maybe you have a combination with to_enum in
>> mind or rather inject?
>>
>>>  I know this is unconventional, but it's a really nice, compact way of
>>> expressing map and filter in one shot, like list comprehension:
>>>
>>> (1..10).select { |a| a * a if a > 5 }
>>>
>>> Was it ever there, or did I just have a dream about it?  It's easy to
>>> implement... just wondering.
>>
>> Maybe 1.9 has a nifty trick, I don't use it that often yet.
>>
>> As said, inject is always a good candidate for this:
>>
>> irb(main):005:0> (1..10).inject([]) {|r,a| r << (a*a) if a > 5; r}
>
> As Robert was the first to suggest inject I am left with the less
> attractive joices ;)
>
>
> a.map{ |a| a > 5 ? a*a: nil}.compact # does not work for any &blk of course
>
> or
>
> myselection = proc{ |a| a*a if a > 5}
> a.select(&myselection).map(&myselection)
>
> or
>
> module Enumerable
>   def map_selection &blk
>      select( &blk ).map( &blk )
>   end
> end

There's also:

   res = []
   (1..10).each {|e| res << (e * e) if e > 5 }
   res

No shame in a local variable now and then :-)


David

-- 
Rails training from David A. Black and Ruby Power and Light:
INTRO TO RAILS (Jan 12-15) | ADVANCING WITH RAILS (Jan 19-22) *
Both in Fort Lauderdale, FL      * Co-taught with Patrick Ewing
See http://www.rubypal.com for details
Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2)