输出hash元素的路径及其值

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/jsntghf/article/details/83552753
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"]]

 

展开阅读全文

没有更多推荐了,返回首页