Ruby NoMethodError

Tsa*_*dai 3 ruby ruby-on-rails

好的,我有点新手.我知道这个错误正在发生,因为我没有正确理解如何调用方法.所以你能帮我理解这里出了什么问题吗?

ThingController中的NoMethodError #index undefined方法`initialized?' for Thing :: Backend:Class

从ThingController.rb的错误部分:

class ThingController
  def init_things
   Backend.init_things unless Backend.initialized?    
  end

  t = ThingController.new 
  t.init_things
end
Run Code Online (Sandbox Code Playgroud)

在Backend.rb里面

class Backend
  # checks if the things hash is initialized
  def initialized?
    @initialized ||= false
  end

  # loads things
  def init_things
    puts "I've loaded a bunch of files into a hash"
    @initialized = true
  end
end
Run Code Online (Sandbox Code Playgroud)

我没有正确地调用该方法,我在互联网上找不到任何关于此错误的明确解释.请帮忙.

谢谢

Bry*_*ard 5

似乎问题是您声明的初始化方法Backend是实例方法.当你再调用Backend.initialized?你调用调用类方法initialized?Backend类.这个方法没有定义,所以它提出了NoMethodError.您可以通过使用声明方法来解决此问题def self.initialized?.如果您真的希望这是一个类方法,您可能需要考虑如何组织其余代码.

您可以在http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/找到有关课程与实例方法的更多信息.