【问题标题】:Need Ruby binary tree implementation explanation需要Ruby二叉树实现解释
【发布时间】: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


【解决方案1】:

entries 来自Enumerable,由于我无法解释的原因,documentation for entries 很糟糕。它似乎与to_a 大致等效,使用each 构造数组元素。在没有明确指定接收者的情况下,它被发送到Node 的当前实例。

至于insert_into,它使用Ruby 的eval 方法,可以让您在运行时将文本解释为Ruby 代码。如果您查看传递给 eval 的字符串,您应该能够弄清楚它的作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多