-
-
Save JoshvaR88/6c8ec89ffb93e9a08bd3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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