ruby - 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
解决方案
看起来你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
推荐阅读
- sql - 在 Oracle 视图中应用过滤器
- php - 当我在 DB 中有默认值时,我应该如何在 Laravel 中使用工厂
- flutter - 我们如何等待用户完成点击按钮,直到用户做出他/她的决定(颤抖)?
- python - OSError: [Errno 9] Bad file descriptor 当使用 pip install
- javascript - JSON模式,验证数组中只有一个对象的属性等于值
- r - R中的ggplot2 :: scale_fill_gradient - 自定义颜色
- wordpress - 保护单个 wordpress 页面并针对外部系统的 API 进行身份验证
- java - @Query 与预期类型不匹配 [java.util.Collection (n/a)]
- javascript - 如何使命令 !say 与用户 ID 一起使用?
- c++ - C++ - Windows - 从任务管理器中捕获进程退出