`+': nil can't be coerced into Fixnum (TypeError). Lucky_seven?(numbers)

243 views Asked by At

I have run in to a slight hiccup. I'm sure it's simple but for the life of me can't figure it out.

The function of the method is simple, given an array of "numbers", return true if any 3 consecutive numbers add up to 7, else false.

My code below satisfies the first condition in full, as in any qualifying set of numbers will return true. My problem is that when an array of numbers do not meet the parameters set in the code, instead of false, I get an error of `+': nil can't be coerced into Fixnum (TypeError), any feed back is helpful. Thanks in advance. Please see code below: * is the problem line.

def lucky_sevens?(numbers)
i = 0
while i < numbers.length 
each_number = numbers[i]
next_number = numbers[i+1]
third_number = numbers[i+2]
 **if  (each_number + next_number + third_number) == 7**
           return true
 end

    i += 1
end
end
2

There are 2 answers

6
dingalapadum On

You are trying to access numbers[i+2] . But what happens when i reaches the last element in numbers? Try

while i < (numbers.length-2)

What basically is happening, is that you are accessing an element out of bounds. Also, you should probably put a return false statement after the loop.

0
kparekh01 On

Using the advice above, I made 2 simple changes. Here is the working version.

def lucky_sevens?(numbers)
    i = 0
    while i < (numbers.length - 2) 
    each_number = numbers[i]
    next_number = numbers[i+1]
    third_number = numbers[i+2]
        if(each_number + next_number + third_number) == 7
        return true
        end
    i += 1
    end
return false
end