Code As A Craft

Notes on technology and the web

Fibonacci Sequence in Ruby

So I’m teaching myself Ruby and today I decided to learn how to write a Fibonacci sequence after hearing about them on Twitter. When I first looked at this particular problem, I had an idea of what was supposed to happen but was unsure of how to write the expression in Ruby - that is until I stopped to draw it out on paper. Being a very visual person/learner, I found it helpful to write out the first few numbers of the Fibonacci sequence with pen and paper, and then to sketch in where the variables would go and how they move as the sequence progresses. Once I was able to visualize how the variables leapfrog each other within the loop and are added together for the next number in the Fibonacci sequence, it was much more clear how I needed to write the expression in Ruby. Sometimes you just need to sketch something to see the pattern. By outlining my problem and subsequent solution with pen and paper first, I was able to spend less time writing code. My Fibonacci sequence in Ruby looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Calculate the Fibonacci sequence up to 4 million.

class Fibonacci

    def initialize
        @numA = 1
        @numB = 0
        @fibonacci_number = 0
        @sum = 0
        self.fibonacci_sequence
    end

    def fibonacci_sequence
        while @fibonacci_number < 4000000
            @fibonacci_number = @numA + @numB
            puts "fibonacci_number\'s current value is " + @fibonacci_number.to_s
            @numB = @numA
            @numA = @fibonacci_number
            @sum = @sum + @fibonacci_number
        end
        puts "The sum of the Fibonacci sequence thus far is " + @sum.to_s
    end

end

fibonacciNumber = Fibonacci.new()