好吧,我是个新手。我知道发生这个错误是因为我不能正确理解方法是如何调用的。那么你能帮我理解这里出了什么问题吗?
ThingController#index中的初始化未定义的方法‘NoMethodError?’for Thing::Backend:Class
来自ThingController.rb的错误部分:
class ThingController
def init_things
Backend.init_things unless Backend.initialized?
end
t = ThingController.new
t.init_things
endBackend.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我没有正确地调用这个方法,并且我在互联网上找不到任何关于这个错误的明确解释。请帮帮忙。
谢谢
发布于 2011-04-21 12:46:31
问题似乎在于您在Backend中声明的初始化方法是一个实例方法。然后,当您调用Backend.initialized?时,您调用的是Backend类的类方法initialized?。此方法未定义,因此会引发NoMethodError。可以通过使用def self.initialized?声明该方法来解决此问题。如果您真的希望它成为一个类方法,那么您可能需要考虑如何组织您的其余代码。
您可以在http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/上找到有关类方法与实例方法的更多信息
发布于 2011-04-21 12:42:34
您已经将initialized?声明为一个实例方法,但是调用它的方式就好像它是一个类方法一样。Here's an explanation of the difference between instance methods and class methods.
https://stackoverflow.com/questions/5739547
复制相似问题