我用 Ruby 编写了一个非常基本的 finance 模块来简化我自己的计算,因为有时输入 irb
并开始调用函数要容易得多。但奇怪的是,在我的模块中,我有一个子模块,其中包含一个名为 future_value (Finance::CompoundInterest.future_value
) 的方法......但是根据 irb
它没有存在吗?它很小,但我真的更希望能够使用复利而不是每次都必须输入公式。
在 irb
中加载时,不会抛出任何错误或警告,并且该方法对于所有意图和目的都是不可见的。几乎可悲的是,我可以实例化一个Finance::Mortgage
。
这是我的财务部门:
module Finance
module CompoundInterest
def future_value(present_value, interest, length)
interest /= 100 if interest >= 1 # if given in percent 1..100
present_value * ((1 + interest)**length)
end
end
class Mortgage
attr_accessor :amount, :rate, :years, :payment, :interest_paid
def initialize(amount, rate, years)
@amount, @rate, @years = amount, rate, years
i = rate / 12
n = years * 12
m = (1 + i)**n
@payment = ((i * m) / (m - 1)) * amount
@interest_paid = @payment * n - amount
end
end
end
我输错了什么导致出现这种奇怪的情况?我使用的是 Ruby 1.8.7-72。
最佳答案
在方法声明中,您需要在名称前加上“self”。或者使用模块的名称,即
def self.future_value(present_value, interest, length)
或
def CompoundInterest.future_value(present_value, interest, length)
然后它应该会按您预期的那样工作。这与您在类上定义类方法(与实例方法相对)的方式相同。
关于ruby - 如何在 Ruby 的子模块中正确封装方法?我的方法不会出现在任何地方!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/970860/