2011-04-21 80 views
3

好的,我是一個新手。我知道這個錯誤發生,因爲我沒有正確理解如何調用方法。那麼你能幫我理解這裏發生了什麼問題嗎?Ruby NoMethodError

ThingController中的NoMethodError#index 未定義的方法`已初始化?'對於事情::後端:類

從ThingController.rb的示數節:

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

    t = ThingController.new 
    t.init_things 
end 

內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 

我沒有正確調用方法,我無法找到對互聯網上的這個錯誤有任何明確的解釋。請幫忙。

感謝

+0

謝謝大家。你已經回答了我的問題,並幫助我解決了這個問題。 Railstips看起來也是一個非常有用的博客。 – Tsagadai 2011-04-21 05:01:15

回答

4

看來問題是您在Backend中聲明的初始化方法是一種實例方法。當你打電話給Backend.initialized?時,你打電話給Backend類調​​用類方法initialized?。這種方法沒有定義,所以它引發了NoMethodError。你可以通過使用def self.initialized?來聲明方法來解決這個問題。如果你真的希望這是一個類方法,你可能需要考慮其他代碼的組織方式。

你可以找到更多關於類與實例方法的信息在http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/