blob: 78b3387c3b06397a26a5d64665128c10d1a09327 (
plain) (
tree)
|
|
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 # => {}
# { c: true }.compact # => { c: true }
def compact
select { |_, value| !value.nil? }
end
# Replaces current hash with non +nil+ values.
# Returns nil if no changes were made, otherwise returns the hash.
#
# hash = { a: true, b: false, c: nil }
# hash.compact! # => { a: true, b: false }
# hash # => { a: true, b: false }
# { c: true }.compact! # => nil
def compact!
reject! { |_, value| value.nil? }
end
end
|