DZone > Web Dev Zone > Day 16 of 30 Ruby Coding Challenge - Sum Even Numbers in a Fibonacci Sequence

Day 16 of 30 Ruby Coding Challenge - Sum Even Numbers in a Fibonacci Sequence

 

Hey friends!

This is the blog post version of the Youtube video from the 30 Ruby Coding Challenges in 30 Days series

We’ve solved the Fibonacci sequence herehere and here, which means that we have some clues of how to create a Fibonacci sequence :)

Today we want to be a little bit daring by solving the following problem:

I want to sum all even numbers in a Fibonacci sequence

Fibonacci Sequence in Ruby

As you already know, this is one of the solutions:

Ruby

1

def fibonacci_sum(count)

2

    number = 0

3

  sequence = []

4

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

5

    number = item if item <= 1

6

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

7

    sequence << number

8

  end

9

    sequence

10

end

We’re returning a Fibonacci sequence, however, that’s not what we’re looking for

Sum Even Numbers in a Fibonacci Sequence in Ruby

We’re going to:

  • add a local variable called sum
  • then update this variable only if the number is even
  • return the sum variable

Ruby

1

def fibonacci_sum(count)

2

  sum = 0

3

    number = 0

4

  sequence = []

5

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

6

    number = item if item <= 1

7

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

8

    sequence << number

9

10

    sum += number if number % 2 == 0

11

  end

12

  sum

13

end

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

Day 16 of 30 Ruby Coding Challenge - Sum Even Numbers
1.85 GEEK