0

I am trying to solve the problem:

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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

In order to solve this question I am first trying make function or method to make a array of Fibonacci numbers. Then I would take it from there.

I came up with this code:

def fibonacci(array)
    array = []
    result = array[0] + array[1] 
    i = 2

    while result < 4_000_000
        result += array[i]

        i += 1
    end

    result

    array<< result

end

fibonacci([1,2])

And I got this error message:

(eval):18: undefined method `+' for nil:NilClass (NoMethodError) from (eval):33

WHAT AM I DOING WRONG? I feel like I'm doing this all wrong

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
Jermaine
  • 13
  • 1
  • 2
  • *By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.*--Are you claiming that there are only finite many even terms in Fibonacci series, and they are all under four million? Otherwise, the sum will not converge. – sawa Jul 20 '14 at 02:08
  • 1
    If that is not what you intended, then you need to improve your English. Particularly, if that is the case, your use of the word *by* is wrong. – sawa Jul 20 '14 at 02:11

2 Answers2

3

Ruby does not raise exceptions when you look up an out-of-bounds index. Your array parameter is ignored and set to empty array, and then you look up the first and second index of that array. Because the array is empty, both of these return nil, and you can't call + on nil.

Nick McCurdy
  • 17,658
  • 5
  • 50
  • 82
0

Please note that your second line of code:

def fibonacci(array)

  array = []    ####  You put parameters and initialize it again

  result = array[0] + array[1] 

  ...

end

The same question maybe help you:

Fibonacci sequence in Ruby (recursion)

You may need to learn programming system with Ruby.

Community
  • 1
  • 1
blackanger
  • 76
  • 4