Skip to content

Instantly share code, notes, and snippets.

@crwang
Created August 17, 2015 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crwang/6a9d6ab3b248debb5131 to your computer and use it in GitHub Desktop.
Save crwang/6a9d6ab3b248debb5131 to your computer and use it in GitHub Desktop.
hash nested iteration
# In /lib/rails_extensions.rb
class Hash
##
# Iterate over a hash, motified so we have the breadcrumb of keys
# http://stackoverflow.com/questions/9279768/how-do-i-loop-over-a-hash-of-hashes-in-ruby
# Example:
# {"root"=>{:a=>"tom", :b=>{:c => 1, :x => 2}}}.nested_each_pair{|k,v|
# puts k
# puts v
# }
def nested_iterate(keys=[])
self.each_pair do |k,v|
local_keys = keys.clone
if v.is_a?(Hash)
local_keys.push(k)
v.nested_iterate(local_keys) {|k, v, local_keys| yield k, v, local_keys}
else
yield(k,v,local_keys)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment