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
Iterating over a HashYou can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.
Use #each to iterate over a hash.
The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.
Can a hash have multiple values Ruby? Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With