-1

I have an Array of Ruby Hashes that I'm trying to iterate so that I can parse values by key.

forms = {"forms":[{"id":123,"name":"John","created_at":"2021-11-23T21:41:17.000Z"},{"id":456,"name":"Joe","created_at":"2021-11-21T05:17:44.000Z"}]}

forms.each do |form|
  puts form ## {:id=>123, :name=>"John", :created_at=>"2021-11-23T21:41:17.000Z"}
  puts form["id"]
end

This yields the following error:

main.rb:4:in `[]': no implicit conversion of String into Integer (TypeError)

I'm admittedly a big Ruby noob, but can't figure this out. I've also tried puts form[:id] and puts form[":id"] to no avail.

Note: I don't have any control over the Array of Hashes that's being assigned to the forms variable. It's what I get back from an external API call.

littleK
  • 19,521
  • 30
  • 128
  • 188

1 Answers1

1

Your forms is a Hash. If you do each on Hash it passes to the block each key & value pair.

forms.each do |key, value|
  p key # => :forms
  p value # => [{....}]
  p value.map { |v| v[:id] }
end

There's also this, in case the forms always has the forms key (doesn't change)

forms[:forms].map { |v| v[:id] }
razvans
  • 3,172
  • 7
  • 22
  • 30