Skip to content

Instantly share code, notes, and snippets.

@JoshvaR88
Forked from kjakub/gist:be17d9439359d14e6f86
Last active August 29, 2015 14:08
Show Gist options
  • Save JoshvaR88/6c8ec89ffb93e9a08bd3 to your computer and use it in GitHub Desktop.
Save JoshvaR88/6c8ec89ffb93e9a08bd3 to your computer and use it in GitHub Desktop.
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