I used my instincts to write this fibonacci sequence generator using an array. I’m aware there are simpler solutions not using an array. I used an array because originally I wanted to output the entire array (e.g., [0,1,1,2,3]).

Using Iteration

—————

def fibonacci(input)
return input if input == 0 || input == 1
array_of_results = [0,1]
i = 1
until i == input
next_node = array_of_results[-1] + array_of_results[-2]
array_of_results.push(next_node)
i += 1
end
return array_of_results.last
end
p fibonacci(11) #=> returns 89

Recursive

———

def fibonacci_recursive(input)
return input if input == 0 || input == 1
fibonacci_recursive(input-1) + fibonacci_recursive(input-2) if input > 1
end
p fibonacci_recursive(11) #=> returns 89

### Like this:

Like Loading...