{{announcement.body}}
{{announcement.title}}

Day 14 of 30 Ruby Coding Challenge - Fibonacci Sequence the Ruby Way

DZone 's Guide to

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

· Web Dev Zone ·
Free Resource

Hey 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:

Ruby
 







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
 




xxxxxxxxxx
1


 
1
(0..10).each do |number|
2
end



In our example we want to avoid the count mutation (fancy name for change). We can do that by the following code:

Ruby
 




xxxxxxxxxx
1


 
1
(0..count).each do |number|
2
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
 




xxxxxxxxxx
1


 
1
sequence << number if number <= 1
2
sequence << sequence[-1] + sequence[-2] if sequence.length >= 2



The complete code, a little bit leaner with a better strategy, would be:

Ruby
 




xxxxxxxxxx
1


 
1
def fibonacci(count)
2
  sequence = []  
3
  (0..count).each do |number|
4
    sequence << number if number <= 1
5
    sequence << sequence[-1] + sequence[-2] if sequence.length >= 2
6
  end
7
  sequence
8
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!

Courses Twitter Youtube Instagram Linkedin GitHub

Topics:
algorithm, algorithm analysis, coding, coding basics, coding challenges, fibonacci, programming, ruby, ruby on rails, tutorial for beginners

Published at DZone with permission of Alexandre Gama . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}