我刚刚尝试了您的代码,似乎该find
方法在找不到任何内容时返回了另一种对象,因此title
当镜头编号无效时调用该方法不起作用。
例如:
1.9.2-p290 :017 > Dribbble::Shot.find(2)
=> #<Dribbble::Shot:0x007ff96b3ed110 @player=#<Dribbble::Player:0x007ff96b3ed048 @created_at="2009/07/21 19:32:24 -0400", @shots_count=172, @twitter_screen_name="owltastic", @avatar_url="http://dribbble.s3.amazonaws.com/users/4/avatars/original/Meagan-6.jpg?1309446649", @likes_received_count=14937, @name="Meagan Fisher", @location="Brooklyn, NY", @following_count=445, @likes_count=1080, @website_url="http://owltastic.com", @username="owltastic", @url="http://dribbble.com/owltastic", @rebounds_count=3, @draftees_count=44, @id=4, @drafted_by_player_id=1, @followers_count=9979, @comments_received_count=1795, @comments_count=211, @rebounds_received_count=13>, @created_at="2009/07/23 07:07:53 -0400", @short_url="http://drbl.in/c", @image_url="http://dribbble.com/system/users/4/screenshots/2/Picture-2.png?1309017100", @title="Playing with Dribbble", @likes_count=9, @rebound_source_id=nil, @url="http://dribbble.com/shots/2-Playing-with-Dribbble", @rebounds_count=0, @id=2, @image_teaser_url="http://dribbble.com/system/users/4/screenshots/2/Picture-2_teaser.png?1309017100", @height=300, @views_count=13299, @comments_count=2, @width=400>
1.9.2-p290 :018 > Dribbble::Shot.find(3)
=> #<Dribbble::Shot:0x007ff96b3ced50 @created_at=nil, @message="Not found">
在将返回的对象添加到数组之前,您应该区分它是否真的有效。
更新:
经过一番挖掘,我发现无效的镜头在 created_at 属性上返回 nil 值,因此您可以执行以下操作:
@dribbbletimes = []
(1..5).each do |i|
shot = Dribbble::Shot.find(i)
@dribbbletimes << shot.title unless shot.created_at.blank?
end