开发者

ruby recursive looping fails

asdf = [[1,2,3],[11,22,33,44,55,66],[51]]

def recursive(params, index)
 if (index==params.size)
  puts "DONE"
 end

 currentParam = params[index]
 currentParam.each do |sh|
  puts sh
  recursive(params, index+1)
 end

end

recursive(asdf,0)

I was expecting an output like:

1 11 22 33 44 5开发者_开发知识库5 66 51 2 11 22 33 44 55 66 51 3 11 22 33 44 55 66

Instead I get:

1 11 51

And:

Undefined method 'each' for nil:NilClass`


The first problem I see is that the method recursive isn't actually recursive. I will assume the call to traverse was intended to be the recursion.

The second problem is when index == params.size you aren't actually stopping the recursion. You're just printing "DONE" and then continuing. This explains the nil exception.

The third problem is this pattern doesn't match your expectation anyway. Are you sure you intended it to be 1 11 22 33 44 55 66 51 2 11 ... and not 1 11 51 22 51 33 51 44 51 55 51 66 51 2 11 51 22 51 ... ? The latter is what your code is attempting to do, and is in fact what you get if you replace the puts "DONE" with return.

The following is a slightly more elegant way of writing your method:

def recursive2(params)
  return if params.empty?
  params[0].each do |p|
    puts p
    recursive2(params[1..-1])
  end
end

recursive2(asdf)


You have an array of arrays

asdf = [[1,2,3],[11,22,33,44,55,66],[51]]

The array asdf contains three elements, each an array. So, when you index into params with an index of 3 or greater you get back nil. At the very least you will have to traverse through each sub array as well in your outer loop. That, or you can compact it into a single array.

Also, as I noted in a comment, your routine is not recursive at all. You have a method 'recursive' which calls another method 'traverse' inside of a loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜