From: James Edward Gray II Date: 2007-11-14T08:35:32+09:00 Subject: Re: recursion with blocks On Nov 13, 2007, at 5:12 PM, Mike Perham wrote: > Sort of. We'll get there… > I'm still unclear how the actual node is propagated back up as > the result of the find call due to the name == "right" block returning > true. We're calling a block recursively, just as we would a method. The typical trick for getting a result from that is just to hand a return value back up the call stack. For example: #!/usr/bin/env ruby -wKU class Named def initialize(name, child = nil) @name = name @child = child end def find_by_name(&block) if block[@name] self elsif @child @child.find_by_name(&block) end end def to_s @name end end names = %w[one two three].reverse.inject(nil) do |child, name| Named.new(name, child) end puts names.find_by_name { |n| n[0] == ?t } puts names.find_by_name { |n| n == "four" } __END__ Does that make more sense? > Now how do I put this on a class which is an ActiveRecord (i.e. the > find method is already taken)? find() has an alias called detect(), which I don't believe ActiveRecord hides with a method of its own. > BTW Saw your talk at the LSRC. I was very inspired to use Ruby for > everything gluey. :-) Glad to hear it! James Edward Gray II