From: "Hal E. Fulton" Date: 2003-06-19T08:31:31+09:00 Subject: Re: question on blocks and iterators ----- Original Message ----- From: "Markus Jais" Newsgroups: comp.lang.ruby To: "ruby-talk ML" Sent: Wednesday, June 18, 2003 6:18 PM Subject: question on blocks and iterators > hello > > > at the end is a sample code > this does not work as I want. I want to use each_if > to yield only the elements that support a certain criteria and then > do something with this elements. but > here the output is: > > ../bl.rb > e: 5 > e: 8 > e: 9 > 2 > 4 > 5 > 8 > 9 > > I do not want the numbers 2 and 4 to be printed > > I could save the elements in an array and return it but I was wondering if > there is another possibility A couple of minor changes (see comments) and this works: class Array def each_if(b) # no & each do |e| if b.call(e) print "e: ", e, "\n" yield e end end end end a = [2, 4, 5, 8, 9] a.each_if(proc { |x| x > 4 }) { |e| puts e } # one block above is passed as a param But you could also simply do a.select {|x| x>4 }.each {|e| puts e} Couldn't you? The print is just for debugging, right? Hal