aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support
diff options
context:
space:
mode:
authorSean Griffin <sean@thoughtbot.com>2014-06-19 12:01:03 -0600
committerSean Griffin <sean@thoughtbot.com>2014-06-29 13:31:43 -0600
commitb2cf8b251aac39c1e3ce71bc1de34a2ce5ef52b1 (patch)
treed4b765dc9a155a22fed30278c07c63d0fecf453f /activesupport/lib/active_support
parent9ca0f8da2abe735c57eacd9b687ee7c3fae3685d (diff)
downloadrails-b2cf8b251aac39c1e3ce71bc1de34a2ce5ef52b1.tar.gz
rails-b2cf8b251aac39c1e3ce71bc1de34a2ce5ef52b1.tar.bz2
rails-b2cf8b251aac39c1e3ce71bc1de34a2ce5ef52b1.zip
Add `Hash#map_values` to ActiveSupport
Didn't get a chance to convert existing code, I'll skim through the code base to make use of this later this afternoon.
Diffstat (limited to 'activesupport/lib/active_support')
-rw-r--r--activesupport/lib/active_support/core_ext/hash.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/hash/transform_values.rb21
2 files changed, 22 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb
index f68e1662f9..af4d1da0eb 100644
--- a/activesupport/lib/active_support/core_ext/hash.rb
+++ b/activesupport/lib/active_support/core_ext/hash.rb
@@ -6,3 +6,4 @@ require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/hash/transform_values'
diff --git a/activesupport/lib/active_support/core_ext/hash/transform_values.rb b/activesupport/lib/active_support/core_ext/hash/transform_values.rb
new file mode 100644
index 0000000000..6ff7e91212
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/transform_values.rb
@@ -0,0 +1,21 @@
+class Hash
+ # Returns a new hash with the results of running +block+ once for every value.
+ # The keys are unchanged.
+ #
+ # { a: 1, b: 2, c: 3 }.transform_values { |x| x * 2 }
+ # # => { a: 2, b: 4, c: 6 }
+ def transform_values(&block)
+ result = self.class.new
+ each do |key, value|
+ result[key] = yield(value)
+ end
+ result
+ end
+
+ # Destructive +transform_values+
+ def transform_values!
+ each do |key, value|
+ self[key] = yield(value)
+ end
+ end
+end