Ruby:“意外的keyword_end" ...,但所有打开器和关闭器都匹配 [英] Ruby: "Unexpected keyword_end"... but all openers and closers match
问题描述
我正在处理将向用户返回第n个素数的代码块.我在第19行和第22行遇到了意外的keyword_end"语法错误.我在代码中添加了注释,以便您可以轻松找到错误的位置.
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)
我已经看过许多其他有关意外的keyword_end"错误的Stack Overflow问题,但是所有这些问题都是由于作者的代码中有太多结束"而引起的.我相信,经过多次检查,我的代码中的结束"关闭器数量正确
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
还有什么问题呢?
推荐答案
将i ++
编写为i += 1
,将number ++
编写为number += 1
. Ruby不支持++
或--
运算符.请阅读在Ruby中没有增量运算符(++)吗?,并阅读为什么Ruby不支持i ++或i—(increment/decrement运算符)?
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)?
这篇关于Ruby:“意外的keyword_end" ...,但所有打开器和关闭器都匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!