0

Below is a program that implements a tree.

class Tree
    attr_accessor :children, :node_name

    def initialize(name_children=[])
        @children = children
        @node_name = name
    end

    def visit_all(&block)
        visit &block
        children.each {|c| c.visit_all &block}
    end

    def visit(&block)
        block.call self
    end
end

ruby_tree = Tree.new( "Ruby", [Tree.new("Reia"), Tree.new("MacRuby")] )

puts "Visiting a node"
ruby_tree.visit {|node| puts node.node_name}
puts 

puts "visiting entire tree"
ruby_tree.visit_all {|node| puts node.node_name}

When I run this code it errors at this line

ruby_tree = Tree.new( "Ruby", [Tree.new("Reia"), Tree.new("MacRuby")] )

The error I'm receiving is

tree.rb:6:in `initialize': undefined local variable or method `name' for #<Tree:0x007f94020249f8 @children=nil> (NameError)
from tree.rb:19:in `new'
from tree.rb:19:in `<main>'

Any help would be awesome.

2
  • What is your question? Commented Oct 11, 2015 at 16:14
  • In your constructor, (initialize), why aren't you entering the variables children, and name as such instead of a children_name ? What it seems to me is that when you are trying to instantiate the class by creating the objects, when it goes to the initialize constructor, it does not find a name in there. Commented Oct 11, 2015 at 16:23

4 Answers 4

3

You have a typo in your initialize method accepts a single argument named name_children, but from the body of that method it looks like the underscore should have been a comma - name, children.

Sign up to request clarification or add additional context in comments.

Comments

1

Here's the problem - line 6 @node_name = name. Where do you define that variable?

Comments

0

In your constructor, (initialize), why aren't you entering the variables children, and name as such instead of a children_name ? What it seems to me is that when you are trying to instantiate the class by creating the objects, when it goes to the initialize constructor, it does not find a name in there.

def initialize(name, children=[])
    @children = children
    @node_name = name
en

1 Comment

Thanks for help guys, I fixed up the typo.
0

As you have define attr_accessor :name in your Model so there you have to define Children method in you model like as

def self.name
    # here will be you code which you want 
 end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.