C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Times: To compute a Fibonacci number, we use times to iterate over each position to the current position. We add up the numbers.
Temp: We need to use a temporary value (temp) because we reassign the variable "a" but do not want to lose its value.
Ruby program that computes Fibonacci numbers
def fibonacci(n)
a = 0
b = 1
# Compute Fibonacci number in the desired position.
n.times do
temp = a
a = b
# Add up previous two numbers in sequence.
b = temp + b
end
return a
end
# Write first 15 Fibonacci numbers in sequence.
15.times do |n|
result = fibonacci(n)
puts result
end
Output
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
Also: We could precompute all the needed Fibonacci values and store them in an array. Some small code modifications would be needed.