Removing all empty elements from a hash / YAML?

前端 未结 20 1579
礼貌的吻别
礼貌的吻别 2020-12-07 15:35

How would I go about removing all empty elements (empty list items) from a nested Hash or YAML file?

相关标签:
20条回答
  • 2020-12-07 16:06

    Rails 4.1 added Hash#compact and Hash#compact! as a core extensions to Ruby's Hash class. You can use them like this:

    hash = { a: true, b: false, c: nil }
    hash.compact                        
    # => { a: true, b: false }
    hash                                
    # => { a: true, b: false, c: nil }
    hash.compact!                        
    # => { a: true, b: false }
    hash                                
    # => { a: true, b: false }
    { c: nil }.compact                  
    # => {}
    

    Heads up: this implementation is not recursive. As a curiosity, they implemented it using #select instead of #delete_if for performance reasons. See here for the benchmark.

    In case you want to backport it to your Rails 3 app:

    # config/initializers/rails4_backports.rb
    
    class Hash
      # as implemented in Rails 4
      # File activesupport/lib/active_support/core_ext/hash/compact.rb, line 8
      def compact
        self.select { |_, value| !value.nil? }
      end
    end
    
    0 讨论(0)
  • 2020-12-07 16:06

    our version: it also cleans the empty strings and nil values

    class Hash
    
      def compact
        delete_if{|k, v|
    
          (v.is_a?(Hash) and v.respond_to?('empty?') and v.compact.empty?) or
              (v.nil?)  or
              (v.is_a?(String) and v.empty?)
        }
      end
    
    end
    
    0 讨论(0)
提交回复
热议问题