输出hash元素的路径及其值

class Hash
  def each_path
    raise ArgumentError unless block_given?
    self.class.each_path( self ) { |path, object| yield path, object }
  end

  protected
  def self.each_path( object, path = '', &block )
    if object.is_a?( Hash ) then object.each do |key, value|
        self.each_path value, "#{ path }#{ key }/", &block
      end
    else yield path, object
    end
  end
end

 

具体示例:

 

    paths = []
    complex_hash = Hash[
      :a => { :aa => '1', :ab => '2' },
      :b => { :ba => '3', :bb => '4' }
    ]
    complex_hash.each_path { |path, value| paths << [ path, value ] }
    puts paths.inspect  # => [["a/aa/", "1"], ["a/ab/", "2"], ["b/bb/", "4"], ["b/ba/", "3"]]

 

你可能感兴趣的:(hash)