0

我不明白为什么一开始冠军是赫敏,而在休息之后,冠军变成了零……使用休息有问题吗?

这是我的代码:

def pair(users_with_meeting, paired_users, ordered_keys,week)    

  ordered_keys.each do |key|    
    candidates = users_with_meeting[key] - paired_users  
    unless candidates.empty?  
      champion = candidates.first 
      puts "ok"
      puts champion.inspect.to_s   
      break    
    end     
  end   

  puts champion.inspect.to_s   

  if champion
    meetings.create! week: week, paired_user: champion
    champion.meetings.create! week: week, paired_user: self
  else
    []
  end

end

这是我的终端中出现的内容:

Run options: include {:locations=>{"./spec/models/user_spec.rb"=>[117]}}
ok    
#<User id: 1265, email: "Hermione.Granger@example.com", first_name: "Hermione", last_name: "Granger", uid: "Hermione.Granger@example.com", active: true, admin: false, created_at: "2013-09-15 18:09:16", updated_at: "2013-09-15 18:09:16", reset_date: "2013-04-22">
F

Failures:

  1) test
     Failure/Error: ginny.pair(User.with_meeting_for(week[1]), [], User.with_meeting_for(week[1]).keys.sort.reverse, week[2])
     NameError:
       undefined local variable or method `champion' for #<User:0x007f85189179f0>
     # ./app/models/user.rb:64:in `pair'
     # ./spec/models/user_spec.rb:133:in `block (2 levels) in <top (required)>'
4

1 回答 1

0

您遇到此错误是因为您在与传递给方法champion的块绑定的范围内定义了局部变量。each在此块之外,变量值变为nil。为了防止这种情况,您可以在调用each方法之前预定义变量,如下所示:

def pair(users_with_meeting, paired_users, ordered_keys,week)
  champion = ''
  ordered_keys.each do |key|    
    candidates = users_with_meeting[key] - paired_users  
    unless candidates.empty?  
      champion = candidates.first 
      puts "ok"
      puts champion.inspect.to_s   
      break    
    end     
  end   
  puts champion.inspect.to_s   
  if champion
    meetings.create! week: week, paired_user: champion
    champion.meetings.create! week: week, paired_user: self
  else
    []
  end
end
于 2013-09-15T18:53:58.837 回答