Ruby: “Unexpected keyword_end”… but all openers and closers match

吃可爱长大的小学妹 提交于 2019-12-31 07:33:39

问题


I'm working on a block of code that will return the nth prime to the user. I'm getting "unexpected keyword_end" syntax errors for lines 19 and 22. I put comments in the code so you can find the locations of the errors easily.

def nthPrime(n)
    number = 3
    primeNumber = 1
    i = 0
    primes = [2]
    #Iterates the number until we've found the desired number of primes.
    while primeNumber < n
        #Iterates through the prime numbers already found to locate prime factors.
        while i < primes.length
            #Returns TRUE if a prime factor is found.
            #If no prime factors are found, primeNumber ticks up by one, and the number
            #is added to the list of primes.
            if number % primes[i] != 0
                if i == primes.length
                    primes << number
                    i = 0
                else
                    i ++
                end #Unexpected keyword_end
            end
            number ++
        end #Unexpected keyword_end
    end
    puts number
end

nthPrime(6)

I've looked at a lot of other Stack Overflow questions about the "unexpected keyword_end" error, but all of those issues were caused because the authors had too many "end"s in their code. I believe, after checking many times, that I have the right number of "end" closers in my code

What else could be the issue?


回答1:


Write i ++ as i += 1 and number ++ as number += 1. Ruby don't support ++ or -- operators. Read this question No increment operator (++) in Ruby? and also read Why doesn't Ruby support i++ or i— (increment/decrement operators)?



来源:https://stackoverflow.com/questions/20915012/ruby-unexpected-keyword-end-but-all-openers-and-closers-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!