【发布时间】:2013-12-29 01:04:25
【问题描述】:
我遇到了一个 ruby 二叉树实现,我真的很想用 Enumerable 对代码的某些部分进行一些澄清,这是我以前从未见过的。 我不知道#words 方法对#entries 做了什么?我在 ruby 文档中查找了条目,但仍然感到困惑,#insert_into 方法,节点的值如何以及在哪里存储在 @left、@right 实例变量中?
class Node
attr_reader :word, :count, :left, :right
include Enumerable
def initialize(word)
@word, @count = word, 1
end
def size
size = 1
size += @left.size unless left.nil?
size += @right.size unless right.nil?
size
end
def insert(another_one)
case @word <=> another_one.word
when 1
insert_into(:left, another_one)
when 0
@count += 1
when -1
insert_into(:right, another_one)
end
end
def each
@left.each {|node| yield node } unless @left.nil?
yield self
@right.each {|node| yield node } unless @right.nil?
end
def words
entries.map {|e| e.word }
end
def count_all
self.map { |node| node.count }.reduce(:+)
end
def insert_into(destination, another_one)
var = destination.to_s
eval(%Q{
if @#{var}.nil?
@#{var} = another_one
else
@#{var}.insert(another_one)
end
})
end
【问题讨论】:
-
这段代码非常适合新手在Ruby中探索。我想你可以自己尝试一下。
-
关于代码的哪些部分正在执行的任何帮助,特别是 insert_into 方法和 words 方法。条目的方式、地点和内容是什么???/
标签: ruby binary-tree