Skip to content

Commit 3943831

Browse files
committed
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 rails#48770.
1 parent e81e2e8 commit 3943831

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
1+
* Implement `HashWithIndifferentAccess#to_proc`.
2+
3+
Previously, calling `#to_proc` on `HashWithIndifferentAccess` object used inherited `#to_proc`
4+
method from the `Hash` class, which was not able to access values using indifferent keys.
5+
6+
*fatkodima*
17

28
Please check [7-1-stable](https://github.com/rails/rails/blob/7-1-stable/activesupport/CHANGELOG.md) for previous changes.

activesupport/lib/active_support/hash_with_indifferent_access.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,10 @@ def to_hash
387387
_new_hash
388388
end
389389

390+
def to_proc
391+
proc { |key| self[key] }
392+
end
393+
390394
private
391395
if Symbol.method_defined?(:name)
392396
def convert_key(key)

activesupport/test/hash_with_indifferent_access_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -965,4 +965,13 @@ def non_hash.to_hash
965965
assert_equal :bar, hash_wia[:foo]
966966
assert_equal :baz, hash_wia[:missing]
967967
end
968+
969+
def test_indifferent_to_proc
970+
@strings = @strings.with_indifferent_access
971+
proc = @strings.to_proc
972+
973+
assert_equal 1, proc["a"]
974+
assert_equal 1, proc[:a]
975+
assert_nil proc[:no_such]
976+
end
968977
end

0 commit comments

Comments
 (0)