From: Markus Jais Date: 2003-06-19T16:59:32+09:00 Subject: Re: 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 thanks. that works fine. the print was just for debugging. I will use this for something else than the array class but the example was easier. just for my understanding: what is the difference between using "proc" as in your example and using "&" in the method definition like "def each_if(&b) one thing I found is that the "&b" solution does not work because of syntax reasons. ../bl.rb:20: syntax error a.each_if { |x| x > 4 } { |e| puts e } are there any other differences ?? according to the documentation both create a Proc object. Markus