我刚开始使用Ruby类,正在编写二叉树类。但是,当我打印特定节点的值时,它会打印十六进制内存地址而不是实际值。我在网上看了很多,但我看到的只是放置和打印,这正是我正在尝试的。你如何打印实际价值而不是地址?
class Node
attr_accessor :value,:left,:right
def initialize(newValue)
@value = newValue
@left = nil
@right = nil
end
# In my binary tree class after a value has been inserted into the tree....
current_node = @root
puts current_node.value
当我运行输出时,我得到BinaryTree :: NumericTreeItem:0x007fa101125eb8
感谢您的时间,我为这个微不足道的问题道歉。我确定这是一个简单的修复方法。避风港能够在网上找到其他任何东西。
答案 0 :(得分:1)
您可以覆盖类中的to_s
method来控制在这种情况下打印出来的内容。我将借用上一个答案的例子:
class NumericTreeItem
attr_accessor :numericValue
def initialize(newValue)
@numericValue = newValue
end
def to_s
"NumericTreeItem with value of #{@numericValue}"
end
end
现在当你这样做时:
puts current_node.value
你会看到类似的东西:
NumericTreeItem with value of 5
显示。
答案 1 :(得分:0)
value
中的Node
实例变量包含名为NumericTreeItem
的类的实例。你没有在你的问题中显示那个类是什么,但让我们假装一个像这样定义的时刻:
class NumericTreeItem
attr_accessor :numericValue
def initialize(newValue)
@numericValue = newValue
end
end
然后打印节点中的值:
puts current_node.value.numericValue