11

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

user6127511
  • 297
  • 1
  • 4
  • 16
  • Possible duplicate of [How to iterate over a hash in Ruby?](http://stackoverflow.com/questions/1227571/how-to-iterate-over-a-hash-in-ruby) – Hamms Apr 26 '16 at 01:16

4 Answers4

15

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
4

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
YasirAzgar
  • 1,385
  • 16
  • 15
2

You can do it like this:

hash.each do |key, array|
  array.each do |value|
    # do something
  end
end
Sheharyar
  • 73,588
  • 21
  • 168
  • 215
1
hash.each do |key_N, values_N|
  values_N.each so |values|
  .
  .
  #YourCode
  .
  .
  end
end
Dharmesh Rupani
  • 1,029
  • 2
  • 12
  • 22