为什么我的递归函数不起作用?

时间:2015-02-23 18:32:37

标签: ruby-on-rails ruby neo4j.rb

我有一个基于neo4j.rb的rails模型(Comment)。我的简单方法应该返回子节点数,而是返回一个LocalJumpError(没有给定块(yield))。我做错了什么?

has_many :both, :children, model_class: Comment, unique: true

def get_number_of_replies
    if children.count == 0
      0
    else
      children.count + children.each.get_number_of_replies
    end
end

3 个答案:

答案 0 :(得分:1)

我认为

children.count + children.each.get_number_of_replies

应该是

children.count + children.collect(&:get_number_of_replies).sum

如您的错误所示,each需要阻止。

答案 1 :(得分:1)

你需要遍历每个孩子以获得你想要的结果:

def get_number_of_replies
  if children.count == 0
    0
  else
    total = 0
    children.each do |c|
      total += children.get_number_of_replies
    end
    children.count + total
  end
end

答案 2 :(得分:0)

Brad Werth写的是正确的。问题还在于,当儿童连接双向工作时,我正在创建一个无限循环。所以这是解决方案:

  has_many :out, :children, model_class: Comment, unique: true
  has_one :in, :child_of, model_class: Comment, unique: true

  def get_number_of_replies
    result = 0
    unless children.count() == 0
      result += children.count
      children.each do |child|
        result += child.get_number_of_replies
      end
    end
    result
  end