How do I loop over a hash of hashes?

150,077

Solution 1

Value is a Hash to so you need iterate on it or you can get only values:-

h.each do |key, value|
  puts key
  value.each do |k,v|
    puts k
    puts v
  end
end

or

h.each do |key, value|
  puts key
  value.values.each do |v|
    puts v
  end
end

Solution 2

You'll want to recurse through the hash, here's a recursive method:

def ihash(h)
  h.each_pair do |k,v|
    if v.is_a?(Hash)
      puts "key: #{k} recursing..."
      ihash(v)
    else
      # MODIFY HERE! Look for what you want to find in the hash here
      puts "key: #{k} value: #{v}"
    end
  end
end

You can Then take any hash and pass it in:

h = {
    "x" => "a",
    "y" => {
        "y1" => {
            "y2" => "final"
        },
        "yy1" => "hello"
    }
}
ihash(h)

Solution 3

I little improved Travis's answer, how about this gist:

https://gist.github.com/kjakub/be17d9439359d14e6f86

class Hash

  def nested_each_pair
    self.each_pair do |k,v|
      if v.is_a?(Hash)
        v.nested_each_pair {|k,v| yield k,v}
      else
        yield(k,v)
      end
    end
  end

end

{"root"=>{:a=>"tom", :b=>{:c => 1, :x => 2}}}.nested_each_pair{|k,v|
  puts k
  puts v
}

Solution 4

The simplest way to separate out all three values in this case would be as follows:

h.each do |key, value|
  puts key
  puts value[:link]
  puts value[:size]
end

Solution 5

You can access the values of a hash directly by calling hash.values. In this case you could do something like

> h = {"67676.mpa"=>{:link=>"pool/sdafdsaff", :size=>4556}}
> h.values.each do |key, value|
>   puts "#{key} #{value}"
> end

link pool/sdafsaff
size 4556
Share:
150,077
Matt Elhotiby
Author by

Matt Elhotiby

Interests: Javascript, React and Rails

Updated on December 17, 2020

Comments

  • Matt Elhotiby
    Matt Elhotiby over 3 years

    I have this hash:

     h
     => {"67676.mpa"=>{:link=>"pool/sdafdsaff", :size=>4556}} 
    
    >  h.each do |key, value|
    >     puts key
    >   puts value
    >   end
    67676.mpa
    linkpool/sdafdsaffsize4556
    

    How do I access the separate values in the value hash on the loop?

  • Jakub Kuchar
    Jakub Kuchar almost 10 years
    @Travis R improved answer
  • huzefa biyawarwala
    huzefa biyawarwala over 8 years
    here what if key isn't used anywhere ? . do we need to put a ? in place of key ? ex : |?, array| is this valid syntax for Ruby ?
  • huzefa biyawarwala
    huzefa biyawarwala over 8 years
    here what if key isn't used anywhere ? . do we need to put a ? in place of key ? ex : |?, array| is this valid syntax ?
  • Борис Чиликин
    Борис Чиликин over 8 years
    Keep it, just don't use it. question mark is not valid.
  • Severin
    Severin over 7 years
    @huzefabiyawarwala if the key isn't used in the iteration you should prefix it with an underscore like so |_key, value|