- Read Tutorial
- Watch Guide Video
In this guide we are going to solve a mathematical challenge that asks us to find even fibonacci numbers, the full question is:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Since this is a fairly straightforward problem (assuming that you are familiar with the Fibonacci sequence), we're going to build a more exhaustive solution to further our understanding of Ruby. We're not going to write a one-line code answer for this problem, rather we are going to build a class.
class Fibbing def initialize(max) @num_1 = 0 @i = 0 @sum = 0 @num_2 = 1 @max = max end def even_fibonacci while @i <= @max @i = @num_1 + @num_2 @sum += @i if @i % 2 == 0 @num_1 = @num_2 @num_2 = @i end @sum end end
In this code, we are creating a class that has an initialize method. The initialize method defines a number of variables inside it. Next, we are creating a method called even_fibonacci. In this method, we have a while loop that runs as long as the value of i is greater than the value of max. From there we are adding the value of num1 and num2 to i.
In the next line we are adding the value of i to sum but only if i is even. Lastly, we are setting the value of num_1 to num_2, and num_2 to the iterator variable i since this is how fibonacci numbers are calculated. We are making this entire method return the value of sum.
Next, let's create an instance of the class, and pass the max parameter to it.
result = Fibbing.new(4_000_000) p result.even_fibonacci
The final output is 4613732, which is right.