From: Logan Capaldo Date: 2006-02-09T10:32:36+09:00 Subject: Re: can map/collect return fewer values than are found in the target? On Feb 8, 2006, at 8:18 PM, Kelly Dwight Felkins wrote: > Is there a way for collect to return fewer items than the > enumerable the > collect is running on? It looks to me like > map/collect will return at least one value for each item in the > array -- > I've seen examples of how to return more items, but > not less. > > Is there a way to do this more succinctly: > > VOWELS = %w{a e i o u} > items = %w{ a b c d e f g h i} > new_items = [] > items.each do |item| > new_items << item unless VOWELS.include(item) > end > new_items > > map/collect in ruby seems very similar to map in perl except that > in perl > the block can return zero or more elements. Is there an method in > ruby that > is similar to perl's map? > > Thanks, > > -Kelly new_items = items.reject { |item| VOWELS.include?(item) } or new_items = items.select { |item| true unless VOWELS.include?(item) } or new_items = items.inject([]) { |list, item| list << item unless VOWELS.include?(item); list }