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

Ruby用while循环逐行打印hobbies报undefined method '[]'如何解决?

问题排查及解决

报错原因说明

undefined method '[]' for nil:NilClass的含义是:你尝试对*空值(nil)*调用[]取值方法,nil是Ruby中的空对象,本身不支持[]取值操作,因此触发报错。

触发报错的直接原因是循环条件逻辑错误:
你写的while index < "hobbies".length中,"hobbies"是普通字符串,长度固定为7,但你的people数组只有3个元素。当index自增到3时,people[3]已经超出数组取值范围,返回nil,此时执行nil["hobbies"]就触发了上述报错。

第一层修复:解决报错问题

把循环条件改为遍历people数组的有效长度,即可解决报错:

index = 0
# 遍历people数组的所有有效元素,people.length值为3
while index < people.length
  p people[index]["hobbies"]
  index += 1
end

但该版本仅能逐人打印爱好数组,无法实现每个hobby单独打印为一行的要求。

最终修复:嵌套循环实现单爱好逐行打印

新增一层内层循环,遍历每个用户的hobbies数组的单个元素即可,完全符合用循环实现、仅用p语句的要求:

people_index = 0
# 外层循环遍历每个用户
while people_index < people.length
  current_person = people[people_index]
  hobbies = current_person["hobbies"]
  hobby_index = 0
  # 内层循环遍历当前用户的每一个爱好
  while hobby_index < hobbies.length
    p hobbies[hobby_index]
    hobby_index += 1
  end
  people_index += 1
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:00:04