Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/hash/compact.rb

Overview

Added in active_support 4.1

Instance Method Summary collapse

Instance Method Details

#compactObject

Returns a hash with non nil values.

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


10
11
12
# File 'lib/core_ext/hash/compact.rb', line 10

def compact
  self.select { |_, value| !value.nil? }
end

#compact!Object

Replaces current hash with non nil values.

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


19
20
21
# File 'lib/core_ext/hash/compact.rb', line 19

def compact!
  self.reject! { |_, value| value.nil? }
end