0
0
RubyProgramBeginner · 2 min read

Ruby Program to Print Fibonacci Series

You can print the Fibonacci series in Ruby using a loop like this: fib = [0, 1]; (2...n).each { |i| fib[i] = fib[i-1] + fib[i-2] }; puts fib.join(' ') where n is the number of terms.
📋

Examples

Input5
Output0 1 1 2 3
Input1
Output0
Input0
Output
🧠

How to Think About It

To print the Fibonacci series, start with the first two numbers 0 and 1. Then, for each next number, add the two previous numbers. Repeat this until you reach the desired count of numbers.
📐

Algorithm

1
Get the number of terms to print, n.
2
If n is 0, print nothing and stop.
3
Start with a list containing 0 and 1.
4
For each number from 2 to n-1, calculate the sum of the two previous numbers and add it to the list.
5
Print all numbers in the list separated by spaces.
💻

Code

ruby
puts 'Enter number of terms:'
n = gets.to_i
fib = []
if n > 0
  fib[0] = 0
end
if n > 1
  fib[1] = 1
end
(2...n).each do |i|
  fib[i] = fib[i-1] + fib[i-2]
end
puts fib.join(' ')
Output
Enter number of terms: 5 0 1 1 2 3
🔍

Dry Run

Let's trace the input 5 through the code

1

Input number of terms

n = 5

2

Initialize first two Fibonacci numbers

fib = [0, 1]

3

Calculate next Fibonacci numbers

fib[2] = fib[1] + fib[0] = 1 + 0 = 1 fib[3] = fib[2] + fib[1] = 1 + 1 = 2 fib[4] = fib[3] + fib[2] = 2 + 1 = 3

4

Print the series

0 1 1 2 3

Indexfib[Index]
00
11
21
32
43
💡

Why This Works

Step 1: Start with base cases

The first two Fibonacci numbers are always 0 and 1, so we set fib[0] = 0 and fib[1] = 1.

Step 2: Build the series iteratively

Each next number is the sum of the two previous numbers, calculated using fib[i] = fib[i-1] + fib[i-2].

Step 3: Print the series

After calculating all numbers, we print them joined by spaces to show the Fibonacci series.

🔄

Alternative Approaches

Recursive method
ruby
def fib(n)
  return n if n <= 1
  fib(n-1) + fib(n-2)
end
n = 5
(0...n).each { |i| print fib(i), ' ' }
Simple but inefficient for large n due to repeated calculations.
Using Enumerator
ruby
fib_enum = Enumerator.new do |y|
  a, b = 0, 1
  loop do
    y << a
    a, b = b, a + b
  end
end
n = 5
puts fib_enum.take(n).join(' ')
Elegant and memory efficient for generating Fibonacci numbers lazily.

Complexity: O(n) time, O(n) space

Time Complexity

The loop runs n times to calculate each Fibonacci number once, so time is O(n).

Space Complexity

We store all n Fibonacci numbers in an array, so space is O(n).

Which Approach is Fastest?

The iterative approach is fastest and most efficient compared to recursion, which has exponential time.

ApproachTimeSpaceBest For
Iterative ArrayO(n)O(n)General use, fast and simple
RecursiveO(2^n)O(n)Small n, simple code but slow
EnumeratorO(n)O(1)Lazy evaluation, memory efficient
💡
Use an array to store Fibonacci numbers and build the series iteratively for better performance.
⚠️
Forgetting to handle the cases when n is 0 or 1, which can cause errors or incorrect output.