Search code examples
rubystringstring-length

Assigning a variable the length of a string or array causes a "dynamic constant assignment" error in Ruby


I started working with Ruby today and looked up the appropriate syntax for basic operations. Apparently I wasn't careful enough because the lines calling length below throw the error "dynamic constant assignment". There may be even more mistakes waiting to be uncovered after this is fixed, but for now I will only focus on this error.

def isPalindrome(n)
    m = n.to_s;
    L = m.length; <-- error
    for i in 0..L/2
        if(m[i] != m[L-1-i])
            return false;
        end
    end
    return true;
end

def nthmax(n, a)
    L = a.length; <-- error
    if(n > L)
        return nil;
    end
    a.sort;
    return a[L-n];
end

Searching the error message leads to posts about how the error is thrown when someone tries to assign a constant a value that isn't actually constant. The question given here is not relevant because I'm not trying to make L a constant (this info was added to clarify that the question, at the time I asked it, was not a duplicate, nor is it a duplicate now).


Solution

  • Turns out that if the 1st letter of a variable is capitalized, it's treated as a constant. "L" should be changed to "l".