{:link=>"pool/sdafdsaff", :size=>4556}} > h.each do |key,...">

How do I go through the hash of a ruby โ€‹โ€‹hash

Ok so 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 can i access individual values โ€‹โ€‹in hash x values โ€‹โ€‹in a loop

+57
ruby ruby-on-rails hash
Feb 14 2018-12-14T00:
source share
5 answers

The value is a hash, so you need to iterate over it or you can only get the 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 
+123
Feb 14 2018-12-14T00:
source share

You want to pass through the hash recursively, here is the 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 

Then you can take any hash and pass it:

 h = { "x" => "a", "y" => { "y1" => { "y2" => "final" }, "yy1" => "hello" } } ihash(h) 
+14
Apr 12 '13 at 16:49
source share

I slightly improved Travis's answer, how about this essence:

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 } 
+6
Jul 02 '14 at 4:06 on
source share

The easiest way to separate all three values โ€‹โ€‹in this case is as follows:

 h.each do |key, value| puts key puts value[:link] puts value[:size] end 
+4
Aug 12 '13 at 0:10
source share

You can access the hash values โ€‹โ€‹directly by calling hash.values . In this case, you can 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 
+2
Feb 14 '12 at 15:47
source share



All Articles