我正在尝试将团队名称存储在@wins
或@loss
中,具体取决于与相应密钥相关联的主页和分数。
@leaderboard_info = [{
home_team:"Patriots",
away_team: "Broncos",
home_score: 7,
away_score: 3
},
#more info in hashes.........]
@wins = []
@loss = []
@leaderboard_info.each do |game|
game.each do |key,value|
if value[:home_score] > value[:away_score] #7 > 3
@win << value[:home_team] #Patriots
@loss << value[:away_team] #Broncos
else
@loss << value[:home_team]
@win << value[:away_team]
end
end
end
但我一直遇到这个错误
[]': no implicit conversion of Symbol into Integer (TypeError)
if
语句应该抓住7和3的具体值。然后它应该推送由值存储的团队名称。为什么不工作?我用key[home_score]
等尝试了它,但它仍然不起作用。
答案 0 :(得分:1)
我认为您应该删除双循环并将其更改为:
@leaderboard_info.each do |game|
if game[:home_score] > game[:away_score]
@win << game[:home_team]
@loss << game[:away_team]
else
@loss << game[:home_team]
@win << game[:away_team]
end
end
答案 1 :(得分:1)
问题是你在Hash上调用每个Hash,它会产生(如你的代码所指出的)Hash中每个记录的键和值。所以当你调用value [:home_team]时,你在String(“爱国者”)上使用[]方法。 String上的[]方法需要一个Fixnum(用于分解字符串)。