首页 > 解决方案 > Ruby - NoMethodError,但为什么只是有时?

问题描述

我正在编写一个脚本来为 subreddit 提取评论,分解单个单词,计算它们,并对它们进行排序。大约 70% 的时间我收到此错误:

in `<main>': undefined method `map' for nil:NilClass (NoMethodError) Did you mean?  tap

大约 30% 的时间,脚本按预期工作。为什么会这样?你会如何解决?我是编程新手,所以如果问题是基本的,我不会感到惊讶。这是我的代码:

require 'net/http'
require 'rubygems'
require 'json'

# Pull json file, parse out comments
url = 'https://www.reddit.com/r/askreddit/comments.json?sort=top&t=all&limit=100'
uri = URI(url)
response = Net::HTTP.get(uri)
json = JSON.parse(response)

comments = json.dig("data", "children").map { |child| child.dig("data", "body") }

#Split words into array
words = comments.to_s.split(/[^'\w]+/)

words.delete_if { |a,_| a.length < 5}

#count and sort words
count = Hash.new(0)
words.each { |word| count.store(word, count[word]+1)}
count.delete_if { |_,b| b < 4}
sorted = count.sort_by { |word,count| count}.reverse
puts sorted

标签: ruby

解决方案


看起来你json.dig("data", "children")偶尔会回来nil。优雅处理此问题的一种方法是使用安全导航运算符 (&.)

comments = json.dig("data", "children")&.map { |child| child.dig("data", "body") }

if comments
  # your other logic with comments here
else
  {}
end

推荐阅读