Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

like image 291
user6127511 Avatar asked Apr 26 '16 01:04

user6127511


People also ask

Can you iterate through a hash in Ruby?

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.

How do you iterate through hash?

Use #each to iterate over a hash.

How do I iterate through an array of items in Ruby?

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?

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.


2 Answers

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.

like image 73
tadman Avatar answered Sep 28 '22 10:09

tadman


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
like image 35
YasirAzgar Avatar answered Sep 28 '22 11:09

YasirAzgar