问题
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