Skip to content

Commit

Permalink
Improve Hash#compact! documentation and tests
Browse files Browse the repository at this point in the history
Make it clear what should be returned when no changes were made to the
hash.

  { c: true }.compact! # => nil
  • Loading branch information
opti committed Jun 3, 2016
1 parent 082a515 commit 0dd2344
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
13 changes: 8 additions & 5 deletions activesupport/lib/active_support/core_ext/hash/compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@ 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 # => {}
# hash.compact # => { a: true, b: false }
# hash # => { a: true, b: false, c: nil }
# { c: nil }.compact # => {}
# { c: true }.compact # => { c: true }
def compact
self.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 }
# hash.compact! # => { a: true, b: false }
# hash # => { a: true, b: false }
# { c: true }.compact! # => nil
def compact!
self.reject! { |_, value| value.nil? }
end
Expand Down
8 changes: 8 additions & 0 deletions activesupport/test/core_ext/hash_ext_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,10 @@ def test_compact
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact)
assert_equal(hash_with_only_nil_values, h)

h = @symbols.dup
assert_equal(@symbols, h.compact)
assert_equal(@symbols, h)
end

def test_compact!
Expand All @@ -1012,6 +1016,10 @@ def test_compact!
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact!)
assert_equal({}, h)

h = @symbols.dup
assert_equal(nil, h.compact!)
assert_equal(@symbols, h)
end

def test_new_with_to_hash_conversion
Expand Down

0 comments on commit 0dd2344

Please sign in to comment.