B
Bob Hutchison
Bob Hutchison said:On Jan 6, 2006, at 11:36 PM, James Edward Gray II wrote:
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.
Why not:
elements = tokens.map do |token|
result = nil
[ClassA, ClassB, ClassC].find { |kind| result = kind.parse?
(token) }
end
Because this won't return the proper value from the block. You
need at least to add a line with "result" after the #find.
cut'n'past-o... oops
And then it's much more inelegant than using #detect.
You mean #detect or #select?
elements = tokens.select do |token|
result = nil
[ClassA, ClassB, ClassC].find { |kind| results << kind.parse?
(token) }
result
end
And this is kind of handy too...
elements = tokens.map do |token|
result = nil
[ClassA, ClassB, ClassC].find { |kind| result = [token,
kind.parse?(token)] }
result
end
That's wrong! That's twice I've done that. I'm going to go have a nap
now.
elements = tokens.map do |token|
result = nil
[ClassA, ClassB, ClassC].find { |kind| result = [token, r =
kind.parse?(token)]; r }
result
end
Anyway, I like this version better...
elements = tokens.map do |token|
result = nil
[ClassA, ClassB, ClassC].find { |kind| (result = [token,
kind.parse?(token)]).last }
result
end
or this...
elements = tokens.map do |token|
result = nil
[ClassA, ClassB, ClassC].find do |kind|
if r = kind.parse?(token) then result = [r, kind, token] end
end
result || [nil, nil, token]
end
and you can use "result = (r = kind.parse?(token)) && [r, kind,
token]" if you choose
Cheers,
Bob
----
Bob Hutchison -- blogs at <http://www.recursive.ca/
hutch/>
Recursive Design Inc. -- <http://www.recursive.ca/>
Raconteur -- <http://www.raconteur.info/>
xampl for Ruby -- <http://rubyforge.org/projects/
xampl/>
----
Bob Hutchison -- blogs at <http://www.recursive.ca/
hutch/>
Recursive Design Inc. -- <http://www.recursive.ca/>
Raconteur -- <http://www.raconteur.info/>
xampl for Ruby -- <http://rubyforge.org/projects/xampl/>