Ruby NoMethodError(undefined method ''...' for '....:Class'

i2loujxw  于 2023-05-06  发布在  Ruby
关注(0)|答案(1)|浏览(404)
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时,我一直得到这个错误,所以我猜汇率方法出了问题,但无法弄清楚原因。但我可能忽略了一些非常明显的东西...因为我是一个完全的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)
yvfmudvl

yvfmudvl1#

rate是示例中的示例方法,但CurrencyExchange.rate尝试调用类方法。
要解决这个问题,首先初始化一个示例,然后在该示例上调用rate。此外,rate不接受参数,您需要将变量传递给初始化方法。

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

请注意,初始化器需要4个命名参数。您还需要向new方法传递一个文件。

相关问题