繁体   English   中英

Ruby NoMethodError(未定义方法 ''...' for '...:Class'

[英]Ruby NoMethodError (undefined method ''…' for '…:Class'

require_relative 'json_lookup'
require_relative 'csv_lookup'
require_relative 'error'

BASE_RATE = 'EUR'

class CurrencyExchange

  def initialize(file:, date:, from:, to:)
    @file = file
    @date = date
    @from = from
    @to = to
  end

  def rate
    lookup = find_lookup
    lookup.to_currency / lookup.from_currency
  end

  private
  def find_lookup
    case File.extname(@file)
    when ".json"
      JsonLookup.new(@file, @date, @from, @to)
    when ".csv"
      CsvLookup.new(@file, @date, @from, @to)
    else raise FileError
    end
  end
end

当我在 irb 中运行 CurrencyExchange.rate 时,我不断收到此错误,所以我猜测 rate 方法出了点问题,但无法弄清楚原因。 但我可能遗漏了一些完全明显的东西......因为我是 Ruby 的完整初学者,将不胜感激任何帮助:)

回溯如下..

irb(main):003:0> CurrencyExchange.rate(Date.new(2018, 11, 22), "USD", "GBP")                                            Traceback (most recent call last):
        5: from C:/Ruby26-x64/bin/irb.cmd:31:in `<main>'
        4: from C:/Ruby26-x64/bin/irb.cmd:31:in `load'
        3: from C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        2: from (irb):3
        1: from (irb):3:in `rescue in irb_binding'
NoMethodError (undefined method `rate' for CurrencyExchange:Class)

rate是您示例中的实例方法,但CurrencyExchange.rate尝试调用 class 方法。

为了解决这个问题,首先初始化一个实例并调用然后对该实例进行rate 此外, rate不接受 arguments,您需要将变量传递给初始化方法。

currency_exchange = CurrencyExchange.new(
  file: file, date: Date.new(2018, 11, 22), from: "USD", to: "GBP"
)
currency_exchange.rate

注意初始化器需要 4 个名为 arguments。 您还需要将文件传递给new方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM