首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby NoMethodError

Ruby NoMethodError
EN

Stack Overflow用户
提问于 2011-04-21 12:32:34
回答 2查看 12.1K关注 0票数 3

好吧,我是个新手。我知道发生这个错误是因为我不能正确理解方法是如何调用的。那么你能帮我理解这里出了什么问题吗?

ThingController#index中的初始化未定义的方法‘NoMethodError?’for Thing::Backend:Class

来自ThingController.rb的错误部分:

代码语言:javascript
复制
class ThingController
  def init_things
   Backend.init_things unless Backend.initialized?    
  end

  t = ThingController.new 
  t.init_things
end

Backend.rb内幕

代码语言:javascript
复制
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

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

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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/上找到有关类方法与实例方法的更多信息

票数 5
EN

Stack Overflow用户

发布于 2011-04-21 12:42:34

您已经将initialized?声明为一个实例方法,但是调用它的方式就好像它是一个类方法一样。Here's an explanation of the difference between instance methods and class methods.

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5739547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档