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

时间:2015-02-23 07:57:00

标签: ruby class scope

我的任务是使用类参数创建一个兴趣计算器,但是我很难应用变量/参数。我一直得到一个参数错误(4为0)。此外,如何在我的`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

2 个答案:

答案 0 :(得分:1)

您已经错误地使用了initialize方法("初始化"),因此ruby认为您仍在使用默认的initialize方法,该方法不带参数,因此错误。

答案 1 :(得分:0)

弗雷德里克·张是正确的,但他们也在寻找被舍入的数字“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