Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop over a hash of hashes?

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?

like image 775
Matt Elhotiby Avatar asked Feb 14 '12 15:02

Matt Elhotiby


People also ask

How do you iterate over hash?

Iterating over a Hash You 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 I loop through a hash in Perl?

Loop over Perl hash values Perl allows to Loop over its Hash values. It means the hash is iterative type and one can iterate over its keys and values using 'for' loop and 'while' loop. In Perl, hash data structure is provided by the keys() function similar to the one present in Python programming language.

Can a hash have multiple values?

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

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 
like image 186
shingara Avatar answered Oct 08 '22 04:10

shingara


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) 
like image 29
Travis Reeder Avatar answered Oct 08 '22 05:10

Travis Reeder