Your Fibonacci implementation in Ruby is correct. You can rewrite it in the following way
def fib(n)
if n < 2
n
else
fib(n-1) + fib(n-2)
end
end
The only advantage is that it's a little bit more concise and you don't use any additional variable that, in fact, it's not required.
But apart from that, there is no cost change in terms of time compared to your algorithm. There are a few possible improvements. The recursive algorithm is well known to be slower than the non recursive version.
The Time Complexity of the Fibonacci recursive sequence is O(n^2)
(I'll skip the details of the calculation, there are tons of papers and SO answers available on the topic). There are several variations.
One quick improvement is to add a cache. This will reduce the computation of the same sub-number in the sequence.
Here's a very quick and dirty example using an Array as storage.
$cache = []
def fib(n)
$cache[n] ||= if n < 2
n
else
fib(n-1) + fib(n-2)
end
end
Just for fun, here's a more compacted, self-contained alternative
def fib(n)
$fibcache ||= []
$fibcache[n] ||= (n < 2 ? n : fib(n-1) + fib(n-2))
end
PS. I used a global variable only as example to demonstrate the memoization pattern. You should use a better system, global variables are almost considered a code smell in Ruby.