【发布时间】:2020-08-21 15:33:09
【问题描述】:
我是 Ruby 新手,目前正在学习数据结构。我已经定义了自己的类,我想将类中的一个方法传递给类中的另一个方法。我尝试执行此操作的方法似乎不起作用。
这是我目前的代码:
class BinaryTree
attr_accessor :left_child, :right_child, :node
def initialize(node, left_child, right_child)
@left_child = left_child
@right_child = right_child
@node = node
end
def to_s
"node: #{@node}, left: #{@left_child}, right: #{@right_child}"
end
def self.print_node
p @node
end
def traverse(some_func)
if !left_child.nil?
left_child.traverse(some_func)
end
if !right_child.nil?
right_child.traverse(some_func)
end
self.some_func
end
end
bst = BinaryTree.new(50,
BinaryTree.new(30, BinaryTree.new(5, nil, nil), BinaryTree.new(20, nil, nil)),
BinaryTree.new(60, BinaryTree.new(45, nil, nil), BinaryTree.new(70, BinaryTree.new(65, nil, nil), BinaryTree.new(80, nil, nil))) )
puts bst.traverse(bst.print_node)
基本上我想遍历二叉树并在每个子节点上调用一些函数。在这种情况下,我只是想传递一个函数来打印节点,但是,此代码会导致以下错误。
`<main>': undefined method `print_node' for #<BinaryTree:0x00007f82f88530b8> (NoMethodError)
我希望有人能解释为什么这会失败,以及我应该做些什么来完成这个。
【问题讨论】:
-
当您编写
self.some_method时,您定义了一个类方法,而当您定义一个没有self的方法时,您定义了一个实例方法。bst是BinaryTree的实例对象,并且只能访问定义的实例方法。我不会评论代码,但删除self应该足以在您尝试访问它时调用 print_node。 -
在
def self.print_node中删除self -
谢谢。这确实有助于访问根节点,但是,它仍然没有在 traverse 方法中调用该方法。我相信,如果我错了,请纠正我,但在调用 bst.traverse(bst.print_node) 时,它正在调用该函数并打印根节点,但之后的所有内容都没有被调用。从遍历中调用该方法的正确方法是什么?调用 self.some_func 似乎是在引用数据的类而不是 BinaryTree 对象的类。
标签: ruby