From: Iain Barnett on 16 Jul 2010 08:07 Hi, I've written the method below to recurse through a non-binary tree of arbitrary depth. I'm still new to Ruby and was wondering if there were some Rubyism's (or just general pointers) that might improve it? Each object 't' holds an array 'children' of objects of the same type as t, which can themselves hold further arrays. Each object also has the attribute 'parent' holding a reference to the parent object. def find_all( block ) selves = [ ] #find_all' f = lambda { |s| if block.call( s ) selves.push( s ) elsif s.children s.children.each { |c| f.call( c ) } else return end } f.call( self ) return selves end Then I can call it like this: t.find_all( lambda { |x| return x if x.whatever_attribute == 'anything' } ) It works, but any thoughts or input are much appreciated. Regards Iain
From: Iain Barnett on 16 Jul 2010 08:23 [Note: parts of this message were removed to make it a legal post.] On 16 Jul 2010, at 13:07, Iain Barnett wrote: > > > Each object 't' ... Pardon me, 't' is the instance of the object here, if that wasn't clear. Iain
From: Jeff Moore on 16 Jul 2010 10:17 Iain Barnett wrote: > On 16 Jul 2010, at 13:07, Iain Barnett wrote: >> >> >> Each object 't' ... > > Pardon me, 't' is the instance of the object here, if that wasn't clear. > > > Iain result = t.flatten.select { |e| e.whatever_attr == "anything" } -- Posted via http://www.ruby-forum.com/.
From: Jeff Moore on 16 Jul 2010 10:23 Jeff Moore wrote: > Iain Barnett wrote: >> On 16 Jul 2010, at 13:07, Iain Barnett wrote: >>> >>> >>> Each object 't' ... >> >> Pardon me, 't' is the instance of the object here, if that wasn't clear. >> >> >> Iain > > result = t.flatten.select { |e| e.whatever_attr == "anything" } oh yes.. should specify some max_depth for flatten max_depth = 99 result = t.flatten(max_depth).select { |e| e.whatever_attr == "anything" } -- Posted via http://www.ruby-forum.com/.
From: Iain Barnett on 16 Jul 2010 15:27 On 16 Jul 2010, at 15:23, Jeff Moore wrote: > Jeff Moore wrote: >> Iain Barnett wrote: >>> On 16 Jul 2010, at 13:07, Iain Barnett wrote: >>>> >>>> >>>> Each object 't' ... >>> >>> Pardon me, 't' is the instance of the object here, if that wasn't clear. >>> >>> >>> Iain >> >> result = t.flatten.select { |e| e.whatever_attr == "anything" } > > oh yes.. > > should specify some max_depth for flatten > > max_depth = 99 > result = t.flatten(max_depth).select { |e| e.whatever_attr == "anything" > } > -- > Posted via http://www.ruby-forum.com/. > Thanks very much. Can't argue with a 12 line into 2 line reduction! :) Iain
|
Pages: 1 Prev: Sinatra + mumboe-soap4r + ruby1.9.1 problem Next: if __FILE__ == $0 & ruby & rdebug & FXRuby |