What is recursion and how does it work?

后端 未结 4 1053
南方客
南方客 2020-12-12 14:27

Could someone please explain what exactly recursion is (and how it works in Ruby, if that\'s not too much to ask for). I came across a lengthy code snippet relying on recurs

4条回答
  •  自闭症患者
    2020-12-12 14:55

    To understand recursion, you first need to understand recursion.

    Now, on a serious note, a recursive function is one that calls itself. One classic example of this construct is the fibonacci sequence:

    def fib(n)
      return n if (0..1).include? n
      fib(n-1) + fib(n-2) if n > 1
    end
    

    Using recursive functions gives you great power, but also comes with a lot of responsability (pun intended) and it presents some risk. For instance, you could end up with stack overflows (I'm on a roll) if your recursiveness is too big :-)

提交回复
热议问题