From: Michael Fellinger Date: 2010-12-31T19:32:16+09:00 Subject: Re: a common idiom On Fri, Dec 31, 2010 at 7:12 PM, Michel Demazure wrote: > I often have to write something like > > some_enumerator.collect ... # or collect.with_index ... > .... > next if ... > ... > end.reject(&:nil?) > > Is there a better way to do a "collect_unless_nil", avoiding the double > processing ? > _md For one, you can use #compact instead of #reject. The way I'd do it is: results = [] some.each do |value| results << value.operation if value.condition? end And then you could also use inject, which is a bit harder to grasp at a glance and a bit more wordy, but some people believe you should avoid variables outside of blocks at all costs... even if you end up assigning the results to one. some.inject [] do |results, value| next results unless value.condition? results << value.operation end Also, at least since 1.9, you can use `some.each_with_index` or `some.to_enum.with_index.inject`. -- Michael Fellinger CTO, The Rubyists, LLC