ruby中的错误代码

ruby中的错误代码,ruby,Ruby,我正在寻找一些关于我的代码的帮助 # save text file to string data = File.read("workdata.txt") # split string into blocks of text relevant to each journey journeys = data.split(/\n\s\n/) # store the amount of journeys as a variable called journeys_size journeys_size

我正在寻找一些关于我的代码的帮助

# save text file to string
data = File.read("workdata.txt")

# split string into blocks of text relevant to each journey
journeys = data.split(/\n\s\n/)

# store the amount of journeys as a variable called journeys_size
journeys_size = journeys.length

# split each journey into lines and save to an array called "journey_lines"
@journey_lines = journeys.map { |i| i.split(/\n/) }

# cretae an array called "all_journey_objects" to hold all journeys
all_journey_objects = []   

# step through the journey arrays 
@journey_lines.each do |line|

next if line[0].include?("position") # skip the journey block of text if it contains position

destinations = []
destination1 = line[12].upcase 
destination2 = line[13].scan(/[a-z]+/i).join(" ").upcase
#   destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase   # <---- When i uncomment this line **
#   destination4 = line[15].scan(/[a-z]+/i).join(" ").upcase
#   destination5 = line[16].scan(/[a-z]+/i).join(" ").upcase

puts destination1
puts destination2
#   puts destination3   #  <---- When i uncomment this line **
#   puts destination5
#   puts destination4

#   journey = Journey.new(line[0] , line[1] , line[6] , destinations, etas, windows)
#   all_journey_objects << journey
end
我遇到的问题是执行时出现以下错误:

watcher.rb:47: in 'block in <main>': undefined method'scan' for nil:NilClass (NoMethodError)
我想原因是因为我正在使用的workdata.txt文件包含一些只有两个目的地的旅程。因此,只要我取消注释这些行以创建第三个目标变量,它就会抛出一个错误。可能是因为它试图对一个不存在的对象运行一个方法

我一直在想办法解决这个问题。如果第47行是:

destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase
nil的未定义方法“scan”:NilClass表示您正在向nil发送扫描。换句话说,第[14]行是零

您可以简单地添加一条if语句:

if line[14]
  destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase
end
或内联,如果:


错误发生在第47行的文件watcher.rb中。上面的代码没有第47行…对不起,我在开头漏掉了一个部分以缩短我的文章。我知道这可能会让人困惑。第47行和我取消注释的那个行相关,错误消息中似乎缺少方法名:未定义的方法并没有意义。也许你们可以解释一下这段代码应该做什么,这样我们就可以建议一种替代方法。
destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase if line[14]