user6127511
user6127511

Reputation: 307

ruby - iterate through a hash containing key/array value pairs, and iterate through each value

I have an hash that looks like this:

{
  "key1": [
     "value1",
     "value2",
     "value3"
  ],
  "key2": [
     "value1",
     "value2",
     "value3",
     "value4",
     "value5"
  ],
  "key3": [
     "value1"
  ],
  "key4": [
     "value1",
     "value2"
  ]
}

How do I iterate through every keyN, while also looping through all the values in that key?

I have an array with all the keys if that helps.

Thanks

Upvotes: 11

Views: 19835

Answers (3)

YasirAzgar
YasirAzgar

Reputation: 1453

If you are sure about the size of arrays, simply you can do like this,

ha = {:a => [1,2]}

ha.each do |k, (v1, v2)|
   p k
   p v1
   p v2
end

Output
:a
1
2

Upvotes: 4

Dharmesh Rupani
Dharmesh Rupani

Reputation: 1007

hash.each do |key_N, values_N|
  values_N.each so |values|
  .
  .
  #YourCode
  .
  .
  end
end

Upvotes: 1

tadman
tadman

Reputation: 211540

Pretty simple, really:

hash.each do |name, values|
  values.each do |value|
    # ...
  end
end

You can do whatever you want with name and value at the lowest level.

Upvotes: 16

Related Questions