Recurse through array of arrays

I

Iain Barnett

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 =3D [ ]
=20
#find_all'
f =3D lambda { |s|=20
if block.call( s )
selves.push( s )=20
elsif s.children
s.children.each { |c| f.call( c ) }
else
return
end
}
=20
f.call( self )
=20
return selves
end


Then I can call it like this:

t.find_all( lambda { |x| return x if x.whatever_attribute =3D=3D =
'anything' } )

It works, but any thoughts or input are much appreciated.

Regards
Iain=
 
I

Iain Barnett

[Note: parts of this message were removed to make it a legal post.]


Each object 't' ...

Pardon me, 't' is the instance of the object here, if that wasn't clear.


Iain
 
J

Jeff Moore

Iain said:
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" }
 
J

Jeff Moore

Jeff said:
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"
}
 
I

Iain Barnett

oh yes..

should specify some max_depth for flatten

max_depth = 99
result = t.flatten(max_depth).select { |e| e.whatever_attr == "anything"
}

Thanks very much. Can't argue with a 12 line into 2 line reduction! :)

Iain
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top