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

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

def fibonacci_sum(count)

sum = 0

    number = 0

sequence = []

  (0..count).each do |item|

number = item if item <= 1

    number = sequence[-1] + sequence[-2] if item > 1

sequence << number

    sum += number if number % 2 == 0

end

  sum

end


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

def fibonacci(count)

  sequence = []

(0…count).each do |number|

    sequence << number if number <= 1

sequence << sequence[-1] + sequence[-2] if number > 1

  end

sequence

end
```

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

Ruby

```
def fibonacci(count)

sequence = []

  (0..count).each do |number|

sequence << number if number <= 1

    sequence << sequence[-1] + sequence[-2] if number > 1

end

  sequence

end

def sum(array)

# magic here

end

puts sum(fibonacci(10))


### **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](https://youtu.be/Y3W64fXmfkw), 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

def sum(array)

  array.select { |number| number % 2 == 0 }.reduce(:+)

end


The complete code would be:

Ruby

def fibonacci(count)

  sequence = []

(0…count).each do |number|

    sequence << number if number <= 1

sequence << sequence[-1] + sequence[-2] if number > 1

  end

sequence

end

def sum(array)

  array.select { |number| number % 2 == 0 }.reduce(:+)

end

puts sum(fibonacci(10))
```

#ruby #programming #coding #ruby on rails #algorithm #fibonacci #tutorial for beginners #algorithm analysis #coding basics

Day 17 Ruby Coding Challenge - Sum Even Numbers in Fibonacci Sequence - DZone Web Dev
2.70 GEEK