class argument/variable 后续参数中的范围应用程序/参数结果引用
class argument/variable scope application / argument result references in subsequent argument
我的任务是用 class 个参数制作一个利息计算器,但我很难应用 variables/arguments。我一直收到参数错误(4 为 0)。此外,如何在我的“陈述”论证中正确引用 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
方法 ("intitialize"),因此 ruby 认为您仍在使用不带参数的默认初始化方法,因此出现错误。
Frederick Cheung 是正确的,但他们也在寻找要四舍五入的数字 "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
我的任务是用 class 个参数制作一个利息计算器,但我很难应用 variables/arguments。我一直收到参数错误(4 为 0)。此外,如何在我的“陈述”论证中正确引用 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
方法 ("intitialize"),因此 ruby 认为您仍在使用不带参数的默认初始化方法,因此出现错误。
Frederick Cheung 是正确的,但他们也在寻找要四舍五入的数字 "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