'case' 语句在函数中如何工作?

How does 'case' statement work in a function?

我有以下 ruby 代码:

def xyz(n)
  case n
  when 0
    0
  when 1
    1
  else
    xyz(n - 1) + xyz(n - 2)
  end
end

puts xyz(ARGF.gets.to_i)

我执行的代码是:

Ruby$ echo "4" | ruby test.rb

我想知道答案是如何变成3的。我不明白:

xyz(n - 1) + xyz(n - 2)

部分代码。请解释。

是一个recursive函数,通过itself

调用一个函数

以下是每个步骤的不同 steps of the function executionoutput

第 1 步:

def xyz(n)
    n = 4.
    case n
    when 0
        0
    when 1
        1
    else
        n = 4, so it comes here and calls
        xyz(n - 1) + xyz(n - 2)
        xyz(3) + xyz(2) // no result
    end
end

否 o/p 因为两个条件都进行递归调用


第 2 步:

def xyz(n)
    n = 3.
    case n
    when 0
        0
    when 1
        1
    else
        n = 3, so it comes here and calls
        xyz(n - 1) + xyz(n - 2)
        xyz(2) + xyz(1) // recursion stops here as case 1 is 1 // so o/p is 1 for hjere
    end
end

o/p 是一个,因为 xyz(1) 将执行到 1。 当前O/p:1 总体O/p:1


第 3 步:

def xyz(n)
    n = 2.
    case n
    when 0
        0
    when 1
        1
    else
        n = 2, so it comes here and calls
        xyz(n - 1) + xyz(n - 2)
        xyz(1) + xyz(0) // 1
    end
end

这里 o/p 又是 1 因为 xyz(1) 会执行到 1, 当前O/p:1 总体 O/p: 1 + 1 ==> 2


第 4 步:

def xyz(n)
    n = 2.
    case n
    when 0
        0
    when 1
        1 // 1
    else
        n = 1, I wont come here
        xyz(n - 1) + xyz(n - 2)
    end
end

这里 o/p 又是 1 因为 case 1 会执行到 1, 当前O/p:1 总体 O/p: 1 + 1 + 1 ==> 3


所以,最终输出是3