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

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

这个想法是 return 一个包含所有人员及其 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']