To practice recursive processing, we implement a function fib that outputs the nth term of the Fibonacci sequence.
fibonacci.rb
def fib(n)
if n == 0
return 0
end
if n == 1
return 1
end
return fib(n-1) + fib(n-2)
end
fibonacci.rb
require './assert'
[[0,0],[1,1],[2,1],[3,2],[4,3],
[5,5],[6,8],[7,13],[8,21]].each do |index, expected|
assert_equal(expected, fib(index))
end
Chart type ruby-V (Recursive Fibonacci)
Recommended Posts