user6127511 user6127511 - 7 months ago 20
Ruby Question

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

Answer

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.

Comments