难以理解Ruby中的return语句

时间:2015-06-05 01:23:51

标签: ruby recursion

我不明白为什么下面的代码没有返回rate变量。奇怪的是,在return语句的正上方有一个puts语句实际上打印出rate的正确值。

def irr(lower_guess, higher_guess, increment, *amounts)
  rate = lower_guess
  precision_level = 0.1
  while rate <= higher_guess
    present_value = present_value_of_series(rate, *amounts)
    if present_value < 0
      puts "in if 1" #debug
      if present_value >= -precision_level
        puts rate
        return rate
      else
        irr((rate-increment), rate, increment/10, *amounts)
        break
      end
    else
      rate += increment
    end
  end
end

示例方法调用:

irr(0.0001, 0.50, 0.01, -11000, 1966.63, 1959.37, 1952.13, 1944.88, 1937.6399999999999, 1930.3999999999999)

编辑: 添加了样本方法调用

编辑2:我已经应用了@Mark Reed提出的解决方案,现在它可以工作:

def irr(lower_guess, higher_guess, increment, *amounts)
  rate = lower_guess
  precision_level = 0.1
  while rate <= higher_guess
    present_value = present_value_of_series(rate, *amounts)
    if present_value < 0
      if present_value >= -precision_level
        break
      else
        rate = irr((rate-increment), rate, increment/10, *amounts)        
      end
    else
      rate += increment
    end
  end
  return rate
end

2 个答案:

答案 0 :(得分:1)

return rate行不是此方法的唯一返回点。它可能会结束,在这种情况下,返回值隐含在最后一个表达式(while循环)。

将其更改为:

def irr(lower_guess, higher_guess, increment, *amounts)
  #...
  while rate <= higher_guess
    #...
  end
  rate  # here
end

答案 1 :(得分:1)

您需要return递归调用的结果或将rate设置为它。

return irr((rate-increment), rate, increment/10, *amounts)