Ruby - recursive each for n-ary tree

Fixed: see EDIT EDIT

Hey guys,

I'm having trouble writing my own recursive data for an n-ary tree. @elementis the value of node, and @childrenis the array of all connected lower nodes. This is my method:

def each
  yield(@element)

  @children.each { |x|
    x.each { |i| yield i}
  }
  self
end

The problem is that it repeats the bottom elements. For example, if I use this to print a node with the value o and one child c, it will print 'occ' instead of 'oc'. I really don’t know what is going on, so all my attempts at correction were ineffective. Any ideas?

EDIT: I think this may be due to the fact that it somehow calls each of the node values ​​in addition to its assignment, so when it is a string of one character, it will give that character, and then return it again with help .eachcall.

EDIT EDIT: Thanks for reading, everything, but I messed up. The problem is not in this method, but in another in the same class, to_s. to_s will print correctly, but will change the value of the parent node if it is a string. Whenever I tested, I always used to_s in the first place and did not even realize it. Sorry about that. (I can’t let me answer my own question, as I am a beginner).

+3
source share
1 answer

, , - :

class Tree
  def initialize element, children = []
    @element, @children = element, children
  end
  def each &pr
    pr.call(@element)
    @children.each{|x| x.each(&pr)}
    self
  end
end

a = Tree.new('self')
b = Tree.new('parent', [a])
c = Tree.new('grandparent', [b])

c.each{|x| puts x}
# => grandparent
# => parent
# => self

b.each{|x| puts x}
# => parent
# => self

, , , , proc, &pr, yield.

+3

All Articles