Skip to content

Instantly share code, notes, and snippets.

@kjakub
Last active November 14, 2019 17:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save kjakub/be17d9439359d14e6f86 to your computer and use it in GitHub Desktop.
Save kjakub/be17d9439359d14e6f86 to your computer and use it in GitHub Desktop.
Ruby Nested Hash each_pair
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
}
class Hash
def nested_with_array_each_pair
self.each do |k,v|
if v.is_a?(Hash)
v.nested_with_array_each_pair {|c,d| yield c,d}
elsif v.is_a?(Array)
v.each do |item|
if item.is_a?(Hash)
item.nested_with_array_each_pair { |a,b| yield a, b }
else
yield k,item
end
end
else
yield(k,v)
end
end
end
end
h = {"root"=>{:a=>"tom", :b=>{:c => [1,3,:bb => [80,90]], :x => [{:d => {:e => 'nested deep'}},3,4]}}}
h.nested_with_array_each_pair{|k,v|
puts "key: #{k} and value: #{v}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment