`block in <main>':未定义的方法`[]'为nil:NilClass(NoMethodError)

时间:2015-10-29 15:36:38

标签: ruby-on-rails ruby json sqlite

我正在尝试加载远程JSON URL,最终将其存储在SQLite3数据库中。

我正在加载JSON(我认为)然后循环遍历它以将每个JSON值分配给一个变量,然后将该变量构建到db.execute语句中以将其存储到数据库中。

运行代码时收到错误“block in <main>': undefined method [] ' for nil:NilClass (NoMethodError)

链接Undefined method '>' for nil:NilClass <NoMethodError>充满了信息,但我不明白发生了什么。我想知道是否有人可以向我解释我的理解中哪里出错了。

我的代码是:

require 'json'
require 'open-uri'

tournament_url = "http://www.pgatour.com/data/r/033/leaderboard-v2.json"

puts tournament_url

leaderboard = JSON.load(open(tournament_url))

no_of_players = leaderboard['leaderboard']['players'].length

puts "The number of players to be loaded is: #{no_of_players}"

data_array = Array.new

for i in 0..no_of_players
  current_position = leaderboard['leaderboard']['players'][i]['current_position']     
end

如果我在结束循环后写任何代码,它将不会执行。

如果还试图通过说:

检查返回的值
if (leaderboard['leaderboard']['players'][i]['current_position'].nil?)
      current_position = ""
else
      current_position = leaderboard['leaderboard']['players'][i]['current_position']
end

2 个答案:

答案 0 :(得分:2)

Range 0..no_of_players is inclusive.

You probably want to use exclusive version (note three dots):

0...no_of_players

or:

0..no_of_players-1

答案 1 :(得分:2)

.lenth returns the number of array items - so the array position of the last item would be no_of_players.length - 1. Basically you get the error because on the last iteration of the loop you get nil.

Instead I might suggest using .each:

leaderboard['leaderboard']['players'].each do |player|
  current_position = player['current_position']
end