Book Image

Comprehensive Ruby Programming

By : Jordan Hudgens
Book Image

Comprehensive Ruby Programming

By: Jordan Hudgens

Overview of this book

Ruby is a powerful, general-purpose programming language that can be applied to any task. Whether you are an experienced developer who wants to learn a new language or you are new to programming, this book is your comprehensive Ruby coding guide. Starting with the foundational principles, such as syntax, and scaling up to advanced topics such as big data analysis, this book will give you all of the tools you need to be a professional Ruby developer. A few of the key topics are: object-oriented programming, built-in Ruby methods, core programming skills, and an introduction to the Ruby on Rails and Sinatra web frameworks. You will also build 10 practical Ruby programs. Created by an experienced Ruby developer, this book has been written to ensure it focuses on the skills you will need to be a professional Ruby developer. After you have read this book, you will be ready to start building real-world Ruby projects.
Table of Contents (20 chapters)

Implementing an even Fibonacci number algorithm

In this section, 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 4 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...