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

时间:2022-10-30 09:18:24

I've written a very basic finance module in Ruby to ease my own calculations, as sometimes it's just a lot easier to enter irb and start calling functions. But the odd thing is, that in my module I have a submodule with a method called future_value (Finance::CompoundInterest.future_value) ... but according to irb it doesn't exist? It's quite small, but I'd really prefer to be able to use compound interest instead of having to enter the formula each time.

我在Ruby中编写了一个非常基本的财务模块来简化我自己的计算,因为有时输入irb并开始调用函数要容易得多。但奇怪的是,在我的模块中,我有一个带有一个名为future_value(Finance :: CompoundInterest.future_value)的方法的子模块......但根据irb它不存在?它很小,但我真的更喜欢能够使用复利而不必每次都输入公式。

When loading in irb no errors or warnings are thrown, and the method is invisible for all intents and purposes. Almost sadly, I can instantiate a Finance::Mortgage.

在irb中加载时,不会抛出任何错误或警告,并且该方法对于所有意图和目的都是不可见的。几乎可悲的是,我可以实例化一个Finance :: Mortgage。

Here's my finance unit:

这是我的财务部门:

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

What have I mistyped to get this strange situation? I am using Ruby 1.8.7-72.

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

1 个解决方案

#1


In the method declaration you need to prefix the name with "self." or with the name of the module i.e.

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

def self.future_value(present_value, interest, length)

or

def CompoundInterest.future_value(present_value, interest, length)

It should then work as you expect. This is the same way that you define a class method (as opposed to an instance method) on a class.

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

#1


In the method declaration you need to prefix the name with "self." or with the name of the module i.e.

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

def self.future_value(present_value, interest, length)

or

def CompoundInterest.future_value(present_value, interest, length)

It should then work as you expect. This is the same way that you define a class method (as opposed to an instance method) on a class.

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