2017-02-28 86 views
-3

我是ruby初學者。我使用proc類,但我得到錯誤。Ruby錯誤:未定義的方法`each'for nil:NilClass(NoMethodError)

class Timeline 
    attr_accessor :tweets 

    def each(&block) # Block into the proc 
     tweets.each(&block) # proc back into the block 
    end 
end 
timeline = Timeline.new(tweets) 
timeline.each do |tweet| 
    puts tweet 
end 

收到錯誤: -

`each': undefined method `each' for nil:NilClass (NoMethodError) 

如何解決這個問題?請告訴我們!

+4

你'@ tweets'變量是零 – Ilya

回答

1

當你定義attr_accessor :tweets,你剛纔定義2種實例方法:

def tweets 
    @tweets 
end 

def tweets=(tweets) 
    @tweets = tweets 
end 

當你調用tweetseach方法裏面,您只需要調用方法與這個名字,不是一個局部變量,所以你應該設置@在initialize方法的鳴叫,因爲現在你@tweets變量未設置:

class Timeline 
    attr_accessor :tweets # this is just a nice syntax for instance variable setter 
         # and getter 

    def initialize(tweets) 
    @tweets = tweets 
    end 

    def each(&block) # Block into the proc 
    tweets.each(&block) # proc back into the block 
    end 
end 
+0

此代碼不能正常工作。錯誤: - test-1.rb:51:在'

':未定義的局部變量或方法'tweets'for main:Object(NameError) – test

+0

也許你應該定義'tweets'? – Ilya

+0

@harleenkaur,'timeline = Timeline.new(tweets)'在這一行 – Ilya

相關問題