Created
August 17, 2015 15:58
-
-
Save crwang/6a9d6ab3b248debb5131 to your computer and use it in GitHub Desktop.
hash nested iteration
This file contains hidden or 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
# 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