Search code examples
rubyfixnum

Ruby no implicit conversion of Fixnum into String (TypeError)... to_i not working


I am learning Ruby and attempting to solve the following challenge:

Write a method that takes in an integer num and returns the sum of all integers between zero and num, up to and including num.

I've come up with:

def sum_nums(num)
    sum = ""
    num = num.to_i
    if num > 0
        while num > 0
            sum = sum + num
            num = num - 1
        end
    end
    if num == 0
        sum = 0 
    end
    if num < 0
        while x < 0
            sum = sum + num
            num = num + 1
        end
    end
    return sum 
end

Been getting the Fixnum string error on the 6th line and unable to troubleshoot on my own. I tried converting num into an integer, even though that didn't make sense to me, as I've written similar methods not requiring to_i. But completely lost as to the obvious thing that I'm missing.


Solution

  • Your error is a result of trying to add string "" with number num.

    Unlike JavaScript, which will try to convert types, Ruby does not allow you to use different types with math operators (unless they are numerical, such as float or integer).

    Correct line 2 to say: sum = 0.