Day 14 of 30 Ruby Coding Challenge  Fibonacci Sequence the Ruby Way
Day 14 of 30. We're going to solve the famous Fibonacci sequence in a more Ruby Way, which will be much better (hopefully!) than the previous solution
Join the DZone community and get the full member experience.
Join For FreeHey friends!
This is the blog post version of the Youtube video from the 30 Ruby Coding Challenges in 30 Days series
Fibonacci Sequence
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:
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:
xxxxxxxxxx
(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:
xxxxxxxxxx
(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:
xxxxxxxxxx
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:
xxxxxxxxxx
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!
The next coding challenge is solving the same problem recursively, which is usually harder to think about. However, it has an even better syntax. See you there!
Don’t forget to come by and say hi!
Published at DZone with permission of Alexandre Gama. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending

Demystifying SPF Record Limitations

FrontEnd: Cache Strategies You Should Know

Exploring the Capabilities of eBPF

Payments Architecture  An Introduction
Comments