diff options
author | Kasper Timm Hansen <kaspth@gmail.com> | 2016-06-07 19:46:30 +0200 |
---|---|---|
committer | Kasper Timm Hansen <kaspth@gmail.com> | 2016-06-07 19:46:30 +0200 |
commit | 26cb88577ae536f88f83e40ff7949ede3d38c465 (patch) | |
tree | d56a1cfb6c334680b63444a7bdf1780f236ba924 /activesupport | |
parent | 693c86369b9ea54b59534673dd79660df4ffb449 (diff) | |
parent | 0dd23446a32b4e4974572a39582ea4c11475b80a (diff) | |
download | rails-26cb88577ae536f88f83e40ff7949ede3d38c465.tar.gz rails-26cb88577ae536f88f83e40ff7949ede3d38c465.tar.bz2 rails-26cb88577ae536f88f83e40ff7949ede3d38c465.zip |
Merge pull request #25265 from opti/improve/hash_compact
Improve Hash#compact! documentation and tests
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/lib/active_support/core_ext/hash/compact.rb | 13 | ||||
-rw-r--r-- | activesupport/test/core_ext/hash_ext_test.rb | 8 |
2 files changed, 16 insertions, 5 deletions
diff --git a/activesupport/lib/active_support/core_ext/hash/compact.rb b/activesupport/lib/active_support/core_ext/hash/compact.rb index 62ea579c65..f072530e04 100644 --- a/activesupport/lib/active_support/core_ext/hash/compact.rb +++ b/activesupport/lib/active_support/core_ext/hash/compact.rb @@ -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 diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index f0a4c4dddc..e70680c773 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -999,6 +999,10 @@ class HashExtTest < ActiveSupport::TestCase 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! @@ -1012,6 +1016,10 @@ class HashExtTest < ActiveSupport::TestCase 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 |