2017-02-28 21 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) 

?私たちに教えてください!あなたがattr_accessor :tweetsを定義するとき

+4

をご '@のtweets'変数は、このコードは動作しません – Ilya

答えて

1

、あなただけの2のインスタンスメソッドを定義します。あなたはeachメソッド内tweetsを呼び出すときに設定する必要がありますので

def tweets 
    @tweets 
end 

def tweets=(tweets) 
    @tweets = tweets 
end 

は、あなただけの、この名前ではなく、ローカル変数とメソッドを呼び出します@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

nilです。エラー: - test-1.rb:51: '

':未定義のローカル変数またはメソッド' tweets' for main:Object(NameError) – test

+0

多分あなたは 'tweets'を定義すべきですか? – Ilya

+0

@harleenkaur、 'timeline = Timeline.new(つぶやき)'この行 – Ilya

関連する問題