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

标签 ruby module methods

我用 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/

相关文章:

ruby - 如何在 Ruby 中获得非插值 bash 转义?

php - 无法在 hmvc laravel 中显示 Controller /路由的 View

javascript - 本地模块node.js :can't load files other than index. js

c++ - 关于将函数作为参数传递的好奇心 - C++

python - 什么方法在 Python 类中调用 `__init__()`

css - Ruby on Rails webfont 不在本地显示

ruby - 使用 Ruby OAuth Gem 将 XML 发布到 OAuth 和签名无效的问题

ruby-on-rails - RubyMine 控制台 : Force Ruby/Rails to abort execution of miss typed statements

Linux模块版本错误 "Invalid module format"

java - 带有参数化类的泛型类型的反射查找方法