Tutorial :ruby recursive looping fails



Question:

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`


Solution:1

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)  


Solution:2

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »