From: Robert Klemme Date: 2006-01-07T22:33:00+09:00 Subject: Re: Iterator Fu Failing Me James Edward Gray II wrote: > I have a group of classes, all implementing a parse?() class method. > Calling parse?(token) will return the constructed object, if it can > be parsed by this class, or false otherwise. > > I want to run a bunch of tokens through these classes, grabbing the > first fit. For example: > > elements = tokens.map do |token| > ClassA.parse?(token) or > ClassB.parse?(token) or > ClassC.parse?(token) > end > > That works. Now can anyone give me a version of the middle section > that doesn't require I call parse?() 50 times? I want something > close to: > > elements = tokens.map do |token| > [ClassA, ClassB, ClassC].find { |kind| kind.parse?(token) } > end > > Except that I want the return result of parse?(), instead of the > class that took it. > > Thanks for any tips you can offer. > > James Edward Gray II elements = tokens.map do |tok| parsers.inject(false) {|a,par| a=par.parse(tok) and break a} end alternative using a method definition def parse(token) parsers.each {|par| a=par.parse(token) and return a} false end But the best solution is elements = tokens.map do |tok| parsers.detect {|par| par.parse(tok)} end :-) Kind regards robert