1

非常に単純な再帰メソッドを作成しようとしていますが、機能させることができません。私はここのようなIDを持つ単純なコメント階層を持っています:

1--
   2--
      4--
   3--
      5--

今、私は彼らのIDを配列に保存したい(ツリーの順序)[0]=1, [1]=2, [2]=4, [3]=3, [4]=5

エントリモデルでこの配列の構築を開始します

def comment_tree
  comment = self.comments.find(1) #it's temporary, just to check if it works
  return recur(comment,0)
end

private
def recur(comment,i)
  @tree[i]=comment.id #added attr_accessible :@tree
  if comment.children.any?
    comment.children.each {|c| recur(c,i+1)}
  else
    return
  end
  @tree
end

ブロックは同じカウンター引数recur(4,2)とを2回実行するため、これは機能しませんrecur(3,2)。このarrasインデックスを維持するには、グローバル$ iのようなものが必要ですが、それを行うためのより良い方法があるはずです。@treeの場合も同じですが、recurメソッドからの戻りパラメーターとして使用するためだけに、モデルに新しい変数を追加する必要がありますか?他の場所では使用しません。

4

1 に答える 1

2

これはどう:

def comment_tree
  comment = self.comments.find(1)
  tree = []
  recur(comment, tree)
  tree
end

private
def recur(comment, acc)
  acc << comment.id
  comment.children.each {|c| recur(c, acc) }
end
于 2012-11-23T12:09:50.450 に答える