2017-02-28 90 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

相关问题