Fibonacci sequence in Ruby (recursion)

后端 未结 24 1283
悲&欢浪女
悲&欢浪女 2020-12-01 02:54

I\'m trying to implement the following function, but it keeps giving me the stack level too deep (SystemStackError) error.

Any ideas what the problem mi

24条回答
  •  甜味超标
    2020-12-01 03:41

    Here is something I came up with, I find this more straight forward.

    def fib(n)
      n.times.each_with_object([0,1]) { |num, obj| obj << obj[-2] + obj[-1] }
    end
    fib(10)
    

提交回复
热议问题