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

使用Ruby数组方法添加符合条件元素却得到空数组,该如何修复?

问题修复方案

原代码的核心问题

  • 数组定义错误:array3的写法缺少外层括号,实际会被解析为三个独立数组,而非预期的二维数组。
  • 方法误用:find_index仅返回第一个匹配条件的元素索引,无法遍历所有元素来收集符合条件的项。
  • 判断逻辑错误:代码里用array3.include?(course)检查整个外层数组是否包含目标字符串,而非每个子数组是否包含该课程。

修复后的代码

# 修正数组定义,添加外层括号包裹子数组
array3 = [['Maths', 'Programming', 'Physics'], ['Maths', 'Intro to comp. science', 'Programming'], ['English', 'Intro to comp. science', 'Physics']]
course = 'Programming'    
index = []

# 遍历每个子数组,判断是否包含目标课程并收集
array3.each do |sub_array|
  if sub_array.include?(course)
    index << sub_array
  end
end

puts index.inspect
# 输出结果:[["Maths", "Programming", "Physics"], ["Maths", "Intro to comp. science", "Programming"]]

更简洁的写法(可选)

可以直接用select方法一步筛选出符合条件的子数组:

array3 = [['Maths', 'Programming', 'Physics'], ['Maths', 'Intro to comp. science', 'Programming'], ['English', 'Intro to comp. science', 'Physics']]
course = 'Programming'    
index = array3.select { |sub_array| sub_array.include?(course) }

puts index.inspect

内容的提问来源于stack exchange,提问作者ahailtotheKing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:05:20