如何在Ruby中的子模块中正确封装方法?我的方法不会出现在任何地方!

Rob*_*t K 1 ruby methods module

我在Ruby中编写了一个非常基本的财务模块来简化我自己的计算,因为有时它更容易进入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
Run Code Online (Sandbox Code Playgroud)

我错误地得到了这种奇怪的情况?我使用的是Ruby 1.8.7-72.

mik*_*kej 6

在方法声明中,您需要在名称前加上"self".或者与模块的名称即

def self.future_value(present_value, interest, length)
Run Code Online (Sandbox Code Playgroud)

要么

def CompoundInterest.future_value(present_value, interest, length)
Run Code Online (Sandbox Code Playgroud)

它应该按预期工作.这与在类上定义类方法(而不是实例方法)的方式相同.

  • 因此,只需在模块中编写"def some_method"就可以定义模块实例方法 - 当您编写"include SomeModule"时,它会作为实例方法复制到类中. (4认同)