类参数/变量范围应用程序/后续参数中的参数结果引用



我的任务是制作一个带有类参数的兴趣计算器,但我很难应用变量/参数。我一直收到一个参数错误(0为4)。此外,如何在"statement"参数中正确引用amount参数结果?有什么建议吗?有人能提供见解来帮助我在这种背景下更好地理解范围界定吗?

class InterestCalculator
  attr_accessor :principal, :rate, :years, :times_compounded
  def intitialize(principal, rate, years, times_compounded)
    @principal, @rate, @years, @times_compounded = principal, rate, years, times_compounded
  end
  def amount
    amount = @principal * (1 + @rate / @times_compounded) ** (@times_compounded * @years)
  end  
  def statement
    "After #{@years} I'll have #{amount} dollars!"
  end
end

这些是规格:

describe InterestCalculator do
  before { @calc = InterestCalculator.new(500, 0.05, 4, 5) }
  describe "#amount" do
    it "calculates correctly" do
      expect( @calc.amount ).to eq(610.1)
    end
  end
  describe "#statement" do
    it "calls amount" do
      @calc.stub(:amount).and_return(100)
      expect( @calc.statement ).to eq("After 4 years I'll have 100 dollars!")
    end
  end
end

您输入了initialize方法("initialize"),因此ruby认为您仍在使用不带参数的默认initialize方法,因此出现了错误。

张是正确的,但他们也在寻找四舍五入的数字"eq(610.1)"

def amount
    amount = @principal * (1 + @rate / @times_compounded) ** (@times_compounded * @years)
  end  

应该是…

def amount
    amount = @principal * (1 + @rate / @times_compounded) ** (@times_compounded * @years)
    amount.round(2)
  end  

最新更新