Ruby

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 here, here 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:

def fibonacci_sum(count)
	number = 0
  sequence = []
  (0..count).each do |item|
    number = item if item <= 1
    number = sequence[-1] + sequence[-2] if item > 1
    sequence << number
  end
	sequence
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
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

Math comes handy here. An even number is a number dividable by 2, which in Ruby is represented by

number % 2 == 0

Quite simple, isn’t it? 😬

In the next video, we’re going to explore a decent and beautiful Ruby Way to solve this same problem, see you there :)

Thanks for the visit and see you in the next coding challenge!

Don’t forget to come by and say hi Alex

Courses Twitter Youtube Instagram Linkedin GitHub

Join My Newsletter

You’ll receive coding courses, tutorials and personal posts! I’ll be happy to send them to you, weekly :)