aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/hash/compact.rb
blob: 62ea579c65770e851763bbbfa6f434255704683e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Hash
  # 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 # => {}
  def compact
    self.select { |_, value| !value.nil? }
  end

  # 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 }
  def compact!
    self.reject! { |_, value| value.nil? }
  end
end