Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.