ruby tree class, why does it says there is 2 arguments instead of 1 in initialize?
class Tree
attr_accessor :children, :node_name
def initialize(tree_hash={})
tree_hash.each do |k,v|
@node_name = k
@children = v.map { |k,v| Tree.new(k,v) }
end
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({'grandpa' => {'dad' => {'child 1' => {}, '开发者_Python百科child 2' => {} },'uncle' => {'child 3' => {}, 'child 4' => {} } } })
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}
And the error message: (I am using ruby 1.9.2)
C:\ruby>ruby tree.rb
tree.rb:4:in `initialize': wrong number of arguments (2 for 1) (ArgumentError)
from tree.rb:7:in `new' from tree.rb:7:in `block (2 levels) in initialize' from tree.rb:7:in `each' from tree.rb:7:in `map' from tree.rb:7:in `block in initialize' from tree.rb:5:in `each' from tree.rb:5:in `initialize' from tree.rb:21:in `new' from tree.rb:21:in `<main>'
There are 2 args in the line:
@children = v.map { |k,v| Tree.new(k,v) }
Maybe you want to change k,v
to {k => v}
?
@children = v.map { |k,v| Tree.new(k=>v) }
I think the initialisation is problematic though- what kind of tree are you implementing?
精彩评论