Jasmine Lognnes Jasmine Lognnes - 4 months ago 7
Ruby Question

How to loop inside a hash?

If I have a hash like the one below, and I want to loop over the second level keys.

Why does this fail?

hash["Element"].each do |id|
h[id] = hash[id]["Name"]
end


hash

{
"Element" => {
"499723" => {
"Name" => "A",
},
"499725" => {
"Name" => "B",
},
}

Answer

It fails because using .each on a Hash yields the tuple of key and value.

hash = {
  "Element" => {
    "499723" => {
      "Name" => "A",
     },
    "499725" => {
      "Name" => "B",
     },
  }
}

hash["Element"].each do |id|
  p id
end

["499723", {"Name"=>"A"}]
["499725", {"Name"=>"B"}]

Therefore, you need to use

hash["Element"].each do |id, value|
  # ...
end

If you don't need the value

hash["Element"].each do |id, _|
  # ...
end

However, you can keep the value and access it directly

hash["Element"].each do |id, value|
  h[id] = value["Name"]
end

A simple solution in your case is to use Enumberable#each_with_object in combination with the previous information:

hash["Element"].each_with_object({}) do |(id, value), acc|
  acc[id] = value["Name"]
end

# => {"499723"=>"A", "499725"=>"B"}