Implement `HashWithIndifferentAccess#to_proc`

Previously, calling `#to_proc` on `HashWithIndifferentAccess` object used inherited `#to_proc`
method from the `Hash` class, which was not able to access values using indifferent keys.

Fixes #48770.
This commit is contained in:
fatkodima 2023-10-03 21:26:08 +03:00
parent e81e2e889d
commit 39438318c7
3 changed files with 19 additions and 0 deletions

View File

@ -1,2 +1,8 @@
* Implement `HashWithIndifferentAccess#to_proc`.
Previously, calling `#to_proc` on `HashWithIndifferentAccess` object used inherited `#to_proc`
method from the `Hash` class, which was not able to access values using indifferent keys.
*fatkodima*
Please check [7-1-stable](https://github.com/rails/rails/blob/7-1-stable/activesupport/CHANGELOG.md) for previous changes.

View File

@ -387,6 +387,10 @@ module ActiveSupport
_new_hash
end
def to_proc
proc { |key| self[key] }
end
private
if Symbol.method_defined?(:name)
def convert_key(key)

View File

@ -965,4 +965,13 @@ class HashWithIndifferentAccessTest < ActiveSupport::TestCase
assert_equal :bar, hash_wia[:foo]
assert_equal :baz, hash_wia[:missing]
end
def test_indifferent_to_proc
@strings = @strings.with_indifferent_access
proc = @strings.to_proc
assert_equal 1, proc["a"]
assert_equal 1, proc[:a]
assert_nil proc[:no_such]
end
end