Question

I have a multi-level tree structure and i'm trying to return an array of ancestors for an object which can have 1-3 ancestors. I have a working method, however it's complex and I would prefer to use a loop, anyone know how I can using ruby?

def ancestors
  @a = []
  @a.push(parent) if parent.present?
  @a.push(@a.last.parent) if @a.last.parent.present?
  @a.push(@a.last.parent) if @a.last.parent.present?
  return @a
end
Was it helpful?

Solution

Assuming I understand your classes right.. I was thinking something like this

def ancestors
   (parent.present? ? [parent, parent.ancestors] :[]).flatten
end

If Parent is present, it returns an array consisting of parent and its ancestors. The flatten is required because each level adds a array layer.

Off topic. return is considered bad style in ruby, and unless you need it, there is no need for this list to be a member variable.

OTHER TIPS

This is a job for recursion. You need to make a function which calls itself. Something like this....

def ancestors 
  if self.parent.present?
    ancestors << self.parent.ancestors
  else
    return self
  end
end

It is fairly simple to do this with an iteration as well, you could try

def ancestors
  @a = []
  anc=parent
  while anc.present? do
    @a.push anc
    anc=anc.parent
  end
  return @a
end

(not tried as I do not have your data structure)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top