From: Kristof Bastiaensen Date: 2004-05-13T20:18:51+09:00 Subject: Re: in search of a compelling reason to use ruby.... On Thu, 13 May 2004 10:22:42 +0200, Robert Klemme wrote: > > Yeah, that's true, although you could do > > a.grep( Criterion.create {|x| x.length > 2} ) {|x| "(#{x})"} > > or even if you define Criterion as method in Kernel: > > a.grep( Criterion {|x| x.length > 2} ) {|x| "(#{x})"} > >> Clever, though, and probably useful in some situations (e.g. where > you're >> doing *lots* of filtering and mapping :) > > Exactly. I thought of a situation where you use this idiom often and you > have Criterion as a lib module that you use over and over again. > Or another idea: require "enumerator" module Enumerable def filter(block) each do |i| yield i if block.call(i) end end def enum_filter(&block) Enumerator.new(self, :filter, block) end end (3..20).enum_filter{ |x| x % 2 == 0 }.collect => [4, 6, 8, 10, 12, 14, 16, 18, 20] Kristof