0

I want to iterate through each value of each array of a hash. Normally, to select a value in an array, I would do this:

array = ["1", "2"]
array.each do |x| puts x end

But how do I iterate through the array if it is in a hash?

This is my code:

hash = {1 => {"a1" => ["un", "uno"], "a2" => ["uunn", "uunnoo"]}, 2 => {"b1" => ["deux", "dos"], "b2" => ["ddeuxx", "ddooss"]}}

hash.each do |key, key2, value|
    puts key
    hash[key].each do |key, value|
        puts key
        #insert here the code to iterate through the array
    end
end

And this is the most logic thing that I found but that don't work:

hash = {1 => {"a1" => ["un", "uno"], "a2" => ["uunn", "uunnoo"]}, 2 => {"b1" => ["deux", "dos"], "b2" => ["ddeuxx", "ddooss"]}}

hash.each do |key, key2, value|
    puts key
    hash[key].each do |key, value|
        puts key
        hash[key][value].each do |value|
            puts value
        end
    end
end

1 Answer 1

1

Solution

Blocks in Hash#each iterate with two variables (|key,value|), and blocks in Array#each iterate with one variable (|element|).

Since you have nested hashes and arrays, you need to apply each multiple times, with different variable names. puts is used with indentation, to better show the structure :

hash = {1 => {"a1" => ["un", "uno"], "a2" => ["uunn", "uunnoo"]}, 2 => {"b1" => ["deux", "dos"], "b2" => ["ddeuxx", "ddooss"]}}

hash.each do |id, sub_hash|
  puts id
  sub_hash.each do |key, sub_array|
    puts "  #{key}"
    sub_array.each do |word|
      puts "    #{word}"
    end
  end
end

It outputs

1
  a1
    un
    uno
  a2
    uunn
    uunnoo
2
  b1
    deux
    dos
  b2
    ddeuxx
    ddooss

Your code

Here's your code with the least amount of modifications :

hash.each do |key1, value1|
    puts key1
    hash[key1].each do |key2, value2|
        puts key2
        hash[key1][key2].each do |value|
            puts value
        end
    end
end

Note that hash[key1] is actually value1, and hash[key1][key2] is value2.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.