繁体   English   中英

嵌套数组 ruby​​ TypeError:没有将哈希隐式转换为整数

[英]nested array ruby TypeError: no implicit conversion of Hash into Integer

def get_att(webinar_id)
  finalArray = []
  api_service = ApiService.new
  response = api_service.get_attendees(webinar_id)
  json = JSON.parse(response.body)

  for x in json['_embedded']['attendeeParticipationResponses']
    first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']
    last_name = json['_embedded']['attendeeParticipationResponses'][x]['lastName']
    email = json['_embedded']['attendeeParticipationResponses'][x]['email']
    finalArray << [first_name, last_name, email]
  end

  # x = 2
  # first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']
  # last_name = json['_embedded']['attendeeParticipationResponses'][x]['lastName']
  # email = json['_embedded']['attendeeParticipationResponses'][x]['email']
  # finalArray << [first_name, last_name, email]

  Rails.logger.info(finalArray)
end

这个想法是返回一个包含所有人员及其 3 个标签的数组。

我知道 JSON 解析数据正在运行,因为注释掉的代码运行良好,我可以更改x分配并运行。 for 循环也有效,因为当我添加计数器时,它会在json['_embedded']['attendeeParticipationResponses']计算 15 个响应。 所以我知道那里有 15 个人,我可以将它们一个一个地添加到最终数组中(顺便说一下,我必须保存多个数组),但是出于某种原因,第二次我将它放入 for 循环中,我得到了奇怪的完全读取的错误:

TypeError: no implicit conversion of Hash into Integer from /Users/josh/Documents/GitHub/schools_health/lib/go_to_webinar/to_pipeline.rb:19:in `[]'

没关系我修好了! 这是一个语法问题。

我来自更多的 Java 背景,并且 ruby​​ 的循环语法使x成为一个对象。 我认为它会包含数组索引。 我通过更改循环内的引用来修复它:

first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']

到:

first_name = x['firstName']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM