Recurse through array of arrays

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

On 16 Jul 2010, at 13:07, Iain B. wrote:

Each object ‘t’ …

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

Iain

Iain B. wrote:

On 16 Jul 2010, at 13:07, Iain B. 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” }

Jeff M. wrote:

Iain B. wrote:

On 16 Jul 2010, at 13:07, Iain B. 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 15:23, Jeff M. wrote:

Iain

Posted via http://www.ruby-forum.com/.

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

Iain

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs