Find every path and it's value in a Hash
This method takes a block as argument which is called each time a the recursivly searched Hash returns a key that does not point to another Hash.
Example:
1 2 paths = [] 3 complex_hash = Hash[ 4 :a => { :aa => '1', :ab => '2' }, 5 :b => { :ba => '3', :bb => '4' } 6 ] 7 complex_hash.each_path { |path, value| paths << [ path, value ] } 8 paths.inspect 9 # => "[[\"b/ba/\", \"3\"], [\"b/bb/\", \"4\"], [\"a/aa/\", \"1\"], [\"a/ab/\", \"2\"]]"
1 2 class Hash 3 def each_path 4 raise ArgumentError unless block_given? 5 self.class.each_path( self ) { |path, object| yield path, object } 6 end 7 8 protected 9 def self.each_path( object, path = '', &block ) 10 if object.is_a?( Hash ) then object.each do |key, value| 11 self.each_path value, "#{ path }#{ key }/", &block 12 end 13 else yield path, object 14 end 15 end 16 end