如何才能收到此代码工作错误消息

时间:2017-12-20 06:07:30

标签: ruby

编写一个取整数n的方法;它应该回来 n*(n-1)*(n-2)*...*2*1。假设n >= 0。 作为特例,factorial(0) == 1。 难度:容易。

def factorial(n)
  a = 1
  store = []
  result = n - a

  while a <= (n-1) 
    j = n * result
    store << j
    a += 1
    store.each |j|
      add each j in array
    end
  end

错误:

  

ruby​​ 2.3.1p112(2016-04-26修订版54768)[x86_64-linux]       (repl):17:语法错误,意外的tIDENTIFIER,期待keyword_do或&#39; {&#39;或者&#39;(&#39;       在数组中添加每个j               ^(repl):32:语法错误,意外的keyword_end,期望输入结束

1 个答案:

答案 0 :(得分:0)

此错误的原因

syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '(' add each j in array ^ (repl):32: syntax error, unexpected keyword_end, expecting end-of-input

是因为您在do

之后缺少store.each
def factorial(n)
  a = 1
  store = []
  result = n - a

  while a <= (n-1) 
    j = n * result
    store << j
    a += 1
    store.each do |j|
      # Not sure what are you trying to do here
      add each j in array
    end
  end
end

你最后还错过了end

注意:此代码仍不会提供预期的输出。先修复你的逻辑。