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
Pardon me, 't' is the instance of the object here, if that wasn't clear.
Iain
···
On 16 Jul 2010, at 13:07, Iain Barnett wrote:
Each object 't' ...
Jeff Moore wrote:
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"
}
···
On 16 Jul 2010, at 13:07, Iain Barnett wrote:
--
Posted via http://www.ruby-forum.com/\.
Thanks very much. Can't argue with a 12 line into 2 line reduction! 
Iain
···
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/\.