提交 a67f25d5 编写于 作者: R Rafael Mendonça França

Merge pull request #13632 from tinogomes/master

Adding Hash#compact and Hash#compact! methods
* Added `Hash#compact` and `Hash#compact!` for removing items with nil value from hash.
*Celestino Gomes*
* Maintain proleptic gregorian in Time#advance
`Time#advance` uses `Time#to_date` and `Date#advance` to calculate a new date.
......
require 'active_support/core_ext/hash/compact'
require 'active_support/core_ext/hash/conversions'
require 'active_support/core_ext/hash/deep_merge'
require 'active_support/core_ext/hash/except'
......
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
......@@ -54,6 +54,8 @@ def test_methods
assert_respond_to h, :deep_stringify_keys!
assert_respond_to h, :to_options
assert_respond_to h, :to_options!
assert_respond_to h, :compact
assert_respond_to h, :compact!
end
def test_transform_keys
......@@ -865,6 +867,32 @@ def test_except_with_mocha_expectation_on_original
original.expects(:delete).never
original.except(:a)
end
def test_compact
hash_contain_nil_value = @symbols.merge(z: nil)
hash_with_only_nil_values = { a: nil, b: nil }
h = hash_contain_nil_value.dup
assert_equal(@symbols, h.compact)
assert_equal(hash_contain_nil_value, h)
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact)
assert_equal(hash_with_only_nil_values, h)
end
def test_compact!
hash_contain_nil_value = @symbols.merge(z: nil)
hash_with_only_nil_values = { a: nil, b: nil }
h = hash_contain_nil_value.dup
assert_equal(@symbols, h.compact!)
assert_equal(@symbols, h)
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact!)
assert_equal({}, h)
end
end
class IWriteMyOwnXML
......
......@@ -2907,6 +2907,16 @@ The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndiffer
NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
### Compacting
The methods `compact` and `compact!` return a Hash without items with `nil` value.
```ruby
{a: 1, b: 2, c: nil}.compact # => {a: 1, b: 2}
```
NOTE: Defined in `active_support/core_ext/hash/compact.rb`.
Extensions to `Regexp`
----------------------
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册