这个 ruby 代码算作递归函数吗?

Does this ruby code count as a recursive function?

我正在阅读有关递归的内容。其中一个练习是编写一个递归函数来对数组中的数字求和。我不应该使用 Array#sum 来执行此操作。我写这个是为了模仿递归:

def recursive_sum(list)
  if list == []
    return 0
  else
    return list.shift + recursive_sum(list)
  end
end

recursive_sum [1,2,3,4]
# => 10

"A recursive function/method calls itself." 这很清楚,看来这个函数确实调用了自己。但是我不确定这是否算作递归函数,因为我在其中使用了 shift 方法。

是的,出于您已经提到的原因,我将其称为递归函数:"A recursive function/method calls itself."

方法调用 shift 没有坏处。事实上,它也会调用其他方法 - 如 if==+

您不能调用任何其他方法,只能调用方法本身,否则该方法将无法执行任何有用的操作。

def foo
  foo
end

调用该递归方法会引发 SystemStackError (stack level too deep).