From 2144e70a86e6403a6298d61862e2e85615cd2a82 Mon Sep 17 00:00:00 2001 From: Josh Pencheon Date: Mon, 10 Apr 2017 01:50:13 +0100 Subject: Implement `fetch_values` for HashWithIndifferentAccess (#28316) `fetch_values` was added to Hash in Ruby 2.3.0: https://bugs.ruby-lang.org/issues/10017 This patch adds an implemention for instances of HWAI, in line with the existing definitions of `fetch` and `values_at`. --- .../lib/active_support/hash_with_indifferent_access.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'activesupport/lib/active_support') diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index 1e1d6d3aac..3b185dd86b 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -195,6 +195,19 @@ module ActiveSupport indices.collect { |key| self[convert_key(key)] } end + # Returns an array of the values at the specified indices, but also + # raises an exception when one of the keys can't be found. + # + # hash = ActiveSupport::HashWithIndifferentAccess.new + # hash[:a] = 'x' + # hash[:b] = 'y' + # hash.fetch_values('a', 'b') # => ["x", "y"] + # hash.fetch_values('a', 'c') { |key| 'z' } # => ["x", "z"] + # hash.fetch_values('a', 'c') # => KeyError: key not found: "c" + def fetch_values(*indices, &block) + indices.collect { |key| fetch(key, &block) } + end if Hash.method_defined?(:fetch_values) + # Returns a shallow copy of the hash. # # hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } }) -- cgit v1.2.3