Hey friends!
This is the blog post version of the Youtube video from the 30 Ruby Coding Challenges in 30 Days series
It’s time to organize the kitchen and to get a better code design to solve the Fibonacci Sequence, which was the previous coding challenge:
We want to calculate the first N numbers in a Fibonacci sequence
This was the last coding solution:
Ruby
def fibonacci(count)
n1 = 0
n2 = 1
sequence = [n1, n2]
while count > 2
# sum of the previous 2 numbers
n3 = n1 + n2
sequence.push(n3)
# assigning the new numbers to calculate the next number in the sequence
n1 = n2
n2 = n3
count = count - 1
end
return sequence
end
puts fibonacci(8)
# 0 1 1 2 3 5 8 13
```
You can be honest, it's not that great.
## The Ruby Way to Solve the Fibonacci Problem
### **Step 1**
Ruby allows us to go from one number to another in a sequence like this:
Ruby
```
(0..10).each do |number|
end
In our example we want to avoid the count mutation (fancy name for change). We can do that by the following code:
Ruby
(0…count).each do |number|
end
```
That’s great because Ruby will **automatically iterate over the array**
### **Step 2**
A better way to store the number in the sequence would be:
Ruby
```
sequence << number if number <= 1
sequence << sequence[-1] + sequence[-2] if sequence.length >= 2
The complete code, a little bit leaner with a better strategy, would be:
Ruby
def fibonacci(count)
sequence = []
(0…count).each do |number|
sequence << number if number <= 1
sequence << sequence[-1] + sequence[-2] if sequence.length >= 2
end
sequence
end
```
Fantastic! Ruby deals with the problem really well!
#ruby #programming #coding #ruby on rails #algorithm #fibonacci #tutorial for beginners #algorithm analysis #coding basics #coding challenges