You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中使用find_all提取所有releases报错的技术求助

解决Ruby中用find_all提取所有匹配项的releases数据问题

问题原因

find方法返回单个匹配的哈希对象,因此可以直接调用['releases'];但find_all返回的是所有匹配条件的游戏哈希组成的数组,数组本身没有['releases']这个键,直接调用会报错。

解决方案

根据需求选择以下两种方式:

1. 保留每个游戏的releases数组结构(得到二维数组)

用map遍历find_all返回的数组,提取每个游戏的releases:

require "JSON"
timeline_na = JSON.load_file 'results/timeline-complete-data.json'
result = timeline_na["games"].find_all { |game| game['representative_name'] }.map { |game| game['releases'] }

返回结果示例:

[
  [{"title"=>"Croc 2", ...}, {"title"=>"Croc 2", ...}],
  [{"title"=>"Spider-Man 2: The Sinister Six", ...}, {"title"=>"Spider-Man 2: Enter the Sinister Six", ...}]
]

2. 合并所有releases为一维数组

如果需要把所有游戏的releases合并成一个数组,用flat_map替代map:

require "JSON"
timeline_na = JSON.load_file 'results/timeline-complete-data.json'
result = timeline_na["games"].find_all { |game| game['representative_name'] }.flat_map { |game| game['releases'] }

返回结果示例:

[
  {"title"=>"Croc 2", ...},
  {"title"=>"Croc 2", ...},
  {"title"=>"Spider-Man 2: The Sinister Six", ...},
  {"title"=>"Spider-Man 2: Enter the Sinister Six", ...}
]

简化写法(Ruby 2.7+)

可以使用下划线参数_1简化代码:

# 二维数组版本
result = timeline_na["games"].find_all { _1['representative_name'] }.map { _1['releases'] }

# 一维数组版本
result = timeline_na["games"].find_all { _1['representative_name'] }.flat_map { _1['releases'] }

内容的提问来源于stack exchange,提问作者Pierre-Luc Gagné

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:46:14