我正在进行在线练习。我被要求创建一个InterestCalculator
类,它在初始化时需要四个参数,并定义了两个函数amount
和statement
。我必须在整个班级中使用self
方法。实例变量只能在initialize
函数中直接访问,amount
只能在一个地方计算。
以下是规格:
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
这是我的代码:
class InterestCalculator
attr_accessor :amount, :statement
def initialize(principal, rate, years, times_compounded)
@principal = principal
@rate = rate
@years = years
@times_compounded = times_compounded
end
def self.amount
amount = principal * (1 + rate / times_compounded) ** (times_compounded * years)
end
def self.statement
statement = "After #{years} years i'll have #{amount} dollars"
end
end
我一直收到以下错误,不知道原因:
RSpec::Expectations::ExpectationNotMetError
expected: 610.1
got: nil
RSpec::Expectations::ExpectationNotMetError
expected: "After 4 years I'll have 100 dollars!"
got: nil
答案 0 :(得分:2)
如果您打算将amount
和statement
作为实例方法,请将代码更改为
def amount
@amount ||= @principal * (1 + @rate / @times_compounded) ** (@times_compounded * @years)
end
def statement
@statement ||= "After #{@years} years i'll have #{amount} dollars"
end
这是因为
def self.my_method
# method body
end
创建一个类方法。此外,如果您希望amount
和statement
为只读,请将attr_accessor
更改为attr_reader
。
答案 1 :(得分:-1)
让它像这样工作:
class InterestCalculator
attr_accessor :amount, :statement, :years
def initialize(principal, rate, years, times_compounded)
@principal = principal
@rate = rate
@years = years
@times_compounded = times_compounded
self.amount = principal * (1 + rate / times_compounded) ** (times_compounded * years)
self.amount = amount.round(1)
end
def statement
statement = "After #{years} years I'll have #{amount} dollars!"
end
end
谢谢!