Removing all empty elements from a hash / YAML?

Removing all empty elements from a hash / YAML?

Asked on January 12, 2019 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    Compact method to Hash:

    class Hash
      def compact
        delete_if { |k, v| v.nil? }
      end
    end
    

    Supports recursion:

    class Hash
      def compact(opts={})
       inject({}) do |new_hash, (k,v)|
        if !v.nil?
          new_hash[k] = opts[:recurse] && v.class == Hash ? v.compact(opts) : v
         end
        new_hash
       end
      end
    end
    

    Answered on January 12, 2019.
    Add Comment

      The  hsh.delete_. In specific case, something : hsh.delete_if { |k, v| v.empty? },

    Answered on January 12, 2019.
    Add Comment

    Hash#compact! as a core extensions to Ruby Hash class.

    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
    # => {}
    

    They implemented it using #select instead of #delete_if for performance reasons.

    # 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
    

    Answered on January 12, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.