NoMethodError 而 MyMethod 确实存在

NoMethodError while MyMethod do exists

我无法理解如何解决这个错误,因为该方法确实存在,我已经用 'Hi' 方法对其进行了测试。

irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> require 'tm'
=> true
irb(main):003:0> Tm.hi
Hey Tm here for duty!
=> nil
irb(main):004:0> hashfile = YAML.load_file('fr.yaml')
=> {"fr"=>{"colors"=>{"yellow"=>"Jaune", "white"=>"Blanc"}, "hello"=>"Bonjour"}}
irb(main):005:0> t = load_translation(hashfile)
Traceback (most recent call last):
        2: from /Users/abderrahmane/.rbenv/versions/2.5.1/bin/irb:11:in `<main>'
        1: from (irb):5 NoMethodError (undefined method `load_translation' for main:Object)

和我的 class:

class Tm

  def self.hi
    puts "Hey Tm here for duty!"
  end

  def auxload(hash, lang, concat='')
    ans = {}
    hash.each do |key, val|
      if val.class == Hash
        aux = auxload(val, lang, concat+key+'.')
        aux.each do |k, v|
          ans[k]=v
        end
      else
        ans[concat+key]={lang => val}
      end
    end
    return ans
  end

  # load the translation from the yaml files
  def load_translation(hash)
    key,value = hash.first
    return auxload(value,key)
  end

end

要在 class 上调用该方法,您首先需要创建 class 的实例,然后在该实例上调用该方法。例如

tm = Tm.new
t = tm.load_translation(hashfile)

您没有从 class Tm 的对象调用 load_translation 方法。

您需要 class 的一个实例:

tm = Tm.new
tm.load_translation(hashfile)

需要先调用load_translation方法,创建class~

实例
tm = Tm.new
tm.load_translation(hashfile)