diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 4dcf958b9d89d..eb573f26bcce4 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -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. diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index 34f2f534971c2..1b1af67115129 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -387,6 +387,10 @@ def to_hash _new_hash end + def to_proc + proc { |key| self[key] } + end + private if Symbol.method_defined?(:name) def convert_key(key) diff --git a/activesupport/test/hash_with_indifferent_access_test.rb b/activesupport/test/hash_with_indifferent_access_test.rb index b1812cbb233aa..b1d6f6c2e73dd 100644 --- a/activesupport/test/hash_with_indifferent_access_test.rb +++ b/activesupport/test/hash_with_indifferent_access_test.rb @@ -965,4 +965,13 @@ def non_hash.to_hash 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