Orsay
Orsay

Reputation: 1130

Iterate into an array of hash

I'm trying to loop into an array of hash :

response = [
  {
    "element" => A,
    "group" => {"created" => 13, "code" => "Paris.rb", :"rsvp_limit" => 40},
    "name" => "CODELAB",
    "venue" => {"id" => 17485302, "place" => "la cordée", "visibility" => "public"}
  },
  {
    "element" => B,
    "group" => {"created" => 13, "code" => "Paris.rb", :"rsvp_limit" => 40},
    "name" => "PARISRB",
    "venue" => {"id" => 17485302, "place" => "la cordée", "visibility" => "public"}
  }
]

When I run

How can I make a loop to have the name of each element of this array of hash ?

I tried :

response.each_with_index do |resp, index|
  puts array[index]["name"]
end

This is the error I get in my console :

NoMethodError: undefined method `[]' for nil:NilClass
from (pry):58:in `block in __pry__'

Upvotes: 0

Views: 67

Answers (2)

guitarman
guitarman

Reputation: 3310

A little bit shorter:

puts response.map{|hash| hash['name']}
# CODELAB
# PARISRB

Upvotes: 3

SirDarius
SirDarius

Reputation: 42889

The array here seems to be a typo. You meant:

response.each_with_index do |resp, index|
  puts resp["name"]
end

The index is not needed because the resp variable is correctly initialized to contain the hash at each iteration.

So it can be simplified to:

response.each do |resp|
  puts resp["name"]
end

Upvotes: 3

Related Questions