' +'字符串不能被强制转换为Fixnum(TypeError)

时间:2015-12-17 10:16:34

标签: ruby excel-formula amortization

这是一个简单的计算公式,我第一次尝试ruby并坚持一个简单的错误bt需要一些指导

#input
loan_amount = 0
rate = 0
period = 0

#output
monthly_payment = 0

print "Enter loan_amount: "
loan_amount = gets.to_f
print "Enter rate: "
rate = gets.to_f
print "Enter period: "
period = gets.to_f

我计算公式时出错我最终得到这个[未定义的main方法:对象(NoMethodError)]

monthly_payment = loan_amount((rate(1 + rate)**period)/(1 + rate)**period - 1)

puts "#{monthly_payment}"

2 个答案:

答案 0 :(得分:1)

方法gets始终返回字符串

loan_amount = gets
=> "1"

您应该在计算之前将字符串转换为数字:

loan_amount = gets
loan_amount = loan_amount.to_f
...

答案 1 :(得分:0)

有一种名为Exonio的宝石:https://github.com/Noverde/exonio。 这个gem实现了一些Excel财务方法,如:PMT,IPMT,PV,NPER ......