tags:

views:

228

answers:

2
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 55 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`

A: 

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.

Ed Swangren
+2  A: 

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)
Kevin Ballard
thanks. replacing return and a few hacks fixed it. im glad some people are still helpful around here.
gweg
Yeah, I don't know why people were downvoting your question. Besides the confusion with traverse vs recursive, your question was perfectly legitimate.
Kevin Ballard
Maybe because the same question has been asked by the same person three times now, each time rewarded with many good answers, and still gweg thinks people are not helpful.
wentbackward
you just prove my point further.
gweg