The Fibonacci Number is another common code challenge and it has some simililraties with the Factorial Number we already solved.

In this videos I show three ways to implement a solution for this problem following similar approaches: iterative loop, recursion and using inject (which is also iterative, but it’s cooler).

  1. Iterative (upto loop):
    1
    2
    3
    4
    5
    6
    7
    
    def fibo(n)
      seq = [0, 1]
      2.upto(n).each do |i|
     seq[i] = seq[i-1] + seq[i-2]
      end
      seq[n]
    end
    
  2. Recursive:
    1
    2
    3
    4
    
    def fibo(n)
      return n if n <= 1
      fibo(n-1) + fibo(n-2)  
    end
    
  3. Using inject:
    1
    2
    3
    4
    
    def fibo(n)
      return n if n <= 1
      (2..n).inject([0,1]){|fib| fib << fib[-1] + fib[-2]}[n]
    end
    

Comments