我给这个代码重构:
$VERBOSE = nil # We'll explain this at the end of the lesson.
require 'prime' # This is a module. We'll cover these soon!
def first_n_primes(n)
unless n.is_a? Integer
return "n must be an integer."
end
if n <= 0
return "n must be greater than 0."
end
prime_array = [] if prime_array.nil?
prime = Prime.new
for num in (1..n)
prime_array.push(prime.next)
end
return prime_array
end
first_n_primes(10)
我被告知要删除第14行中的if语句(prime_array赋值)并将其替换为条件赋值运算符。这是我修改过的代码:
$VERBOSE = nil # We'll explain this at the end of the lesson.
require 'prime' # This is a module. We'll cover these soon!
def first_n_primes(n)
unless n.is_a? Integer
return "n must be an integer."
end
if n <= 0
return "n must be greater than 0."
end
prime_array ||= []
prime = Prime.new
for num in (1..n)
prime_array.push(prime.next)
end
return prime_array
end
first_n_primes(10)
然而,当我编译它时,即使生成的素数组似乎与之前生成的素数无法区分,我仍然会得到错误: &#34;哎呀,再试一次。看起来您没有在代码中正确使用条件赋值运算符。如果您需要帮助,请查看提示!&#34;除了我已经实施的内容之外,提示没有获得任何有用的信息。
是什么给出的?
注意:我不确定这个问题是否适合stackoverflow或者更适合codereview。 它与特定运营商打交道的事实表明前者,而涉及重构的事实表明后者。
答案 0 :(得分:0)
你在第14行[]
之后放了一个空格字符......
如果存在空间,它对我来说也不起作用,没有它 - 它确实如此。
所以这不是你的错,而是他们的错。
答案 1 :(得分:0)
$VERBOSE = nil # We'll explain this at the end of the lesson.
require 'prime' # This is a module. We'll cover these soon!
def first_n_primes(n)
unless n.is_a? Integer
return "n must be an integer."
end
if n <= 0
return "n must be greater than 0."
end
prime_array ||= []
prime = Prime.new
for num in (1..n)
prime_array.push(prime.next)
end
return prime_array
end
first_n_primes(10)