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

Day 17 Ruby Coding Challenge - Sum Even Numbers in Fibonacci Sequence

DZone 's Guide to

Day 17 Ruby Coding Challenge - Sum Even Numbers in Fibonacci Sequence

Day 17 of 30. We're going to sum all the even numbers in a given Fibonacci sequence using a better code design in Ruby

· 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

Today, we want to solve the previous problem in a more Ruby Way

I want to sum all even numbers in a Fibonacci sequence

Last Algorithm Version

This was the last algorithm version of the problem:

Ruby


The code is not that great for a couple of reasons:

  • Too many local variables to manipulate.
  • Two main responsibilities: create the Fibonacci sequence AND validate even numbers.

The two main reasons above leave us with code that's difficult to read, and therefore, difficult to maintain. Fewer friends in our team, right? 

I’m going to try to get rid of these problems. Let’s get into it!

Better Algorithm Version - Ruby Way

I’m going to break the refactoring into a few small steps

Step 1 - Splitting Responsibilities

Let’s create a new method do generate only the Fibonacci sequence

Ruby


Then we’re going to create the method to sum even numbers based on the generated sequence

Ruby


Step 2 - Sum of Even Numbers

Now, we just need to sum all the even numbers, given an array of numbers.

As we did previously here, I’m going to use a Ruby symbol, which allows us to reduce a list of items into a single number by applying an operation:

Ruby


The complete code would be:

Ruby


That’s it! A little bit better version of the previous problem and I hope you liked it!


Do you have a better/different version? Drop that in the comments and bring more healthy discussions!

Thanks for the visit and see you in the next coding challenge. Don’t forget to come by and say hi!

Courses Twitter Youtube Instagram Linkedin GitHub

Topics:
algorithm, algorithm analysis, coding, coding basics, 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 }}