Merge pull request #35080 from sos4nt/add_hash_assoc

Add HashWithIndifferentAccess#assoc
This commit is contained in:
Ryuta Kamizono 2019-01-30 18:05:35 +09:00
commit 9bb07b79e4
3 changed files with 28 additions and 0 deletions

View File

@ -1,3 +1,10 @@
* Add `ActiveSupport::HashWithIndifferentAccess#assoc`.
`assoc` can now be called with either a string or a symbol.
*Stefan Schüßler*
## Rails 6.0.0.beta1 (January 18, 2019) ##
* Remove deprecated `Module#reachable?` method.

View File

@ -164,6 +164,19 @@ module ActiveSupport
super(convert_key(key))
end
# Same as <tt>Hash#assoc</tt> where the key passed as argument can be
# either a string or a symbol:
#
# counters = ActiveSupport::HashWithIndifferentAccess.new
# counters[:foo] = 1
#
# counters.assoc('foo') # => ["foo", 1]
# counters.assoc(:foo) # => ["foo", 1]
# counters.assoc(:zoo) # => nil
def assoc(key)
super(convert_key(key))
end
# Same as <tt>Hash#fetch</tt> where the key passed as argument can be
# either a string or a symbol:
#

View File

@ -447,6 +447,14 @@ class HashWithIndifferentAccessTest < ActiveSupport::TestCase
assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
end
def test_indifferent_assoc
indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
key, value = indifferent_strings.assoc(:a)
assert_equal("a", key)
assert_equal(1, value)
end
def test_indifferent_compact
hash_contain_nil_value = @strings.merge("z" => nil)
hash = ActiveSupport::HashWithIndifferentAccess.new(hash_contain_nil_value)