Search code examples
recursionpathmaze

FInd a path through a maze using recursion


I just have a question about recursive methods. There is this method that I need to write that finds a path through a maze. However, it doesn't take any parameters. So I am wondering can a method that takes no parameters, be recursive?


Solution

  • Yes. In object orientated languages you can recurse over an object and use it to hold and maintain state.

    Here's a quick example in Ruby.

    require 'ostruct'
    
    class Demo < OpenStruct
        def recurse
            return 'finished' if self.value == 10
            puts 'recursing'
            self.value += 1
            self.recurse
        end
    end
    
    Demo.new(value: 1).recurse
    

    In other situations you could refer to a global variable instead.