aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
authorRafael Mendonça França <rafaelmfranca@gmail.com>2012-05-23 07:27:21 -0700
committerRafael Mendonça França <rafaelmfranca@gmail.com>2012-05-23 07:27:21 -0700
commitc1487f619045840d89f1e2dbc6e133e1c2cbf2f4 (patch)
treed27cdae39be7aa69ecaf9e918ecff176a51be268 /guides
parenta6d0e3795790c85dded4f2c396277214508dbc89 (diff)
parent6ff887321b930197a8d62ddd0fc1dcb965ccda29 (diff)
downloadrails-c1487f619045840d89f1e2dbc6e133e1c2cbf2f4.tar.gz
rails-c1487f619045840d89f1e2dbc6e133e1c2cbf2f4.tar.bz2
rails-c1487f619045840d89f1e2dbc6e133e1c2cbf2f4.zip
Merge pull request #6259 from markmcspadden/hash_transform_keys
Add Hash#transform_keys and Hash#transform_keys!
Diffstat (limited to 'guides')
-rw-r--r--guides/source/active_support_core_extensions.textile32
1 files changed, 32 insertions, 0 deletions
diff --git a/guides/source/active_support_core_extensions.textile b/guides/source/active_support_core_extensions.textile
index 80faffa49c..1f92d9d5f5 100644
--- a/guides/source/active_support_core_extensions.textile
+++ b/guides/source/active_support_core_extensions.textile
@@ -2549,6 +2549,38 @@ There's also the bang variant +except!+ that removes keys in the very receiver.
NOTE: Defined in +active_support/core_ext/hash/except.rb+.
+h5. +transform_keys+ and +transform_keys!+
+
+The method +transform_keys+ accepts a block and returns a hash that has applied the block operations to each of the keys in the receiver:
+
+<ruby>
+{nil => nil, 1 => 1, :a => :a}.transform_keys{ |key| key.to_s.upcase }
+# => {"" => nil, "A" => :a, "1" => 1}
+</ruby>
+
+The result in case of collision is undefined:
+
+<ruby>
+{"a" => 1, :a => 2}.transform_keys{ |key| key.to_s.upcase }
+# => {"A" => 2}, in my test, can't rely on this result though
+</ruby>
+
+This method may be useful for example to build specialized conversions. For instance +stringify_keys+ and +symbolize_keys+ use +transform_keys+ to perform their key conversions:
+
+<ruby>
+def stringify_keys
+ transform_keys{ |key| key.to_s }
+end
+...
+def symbolize_keys
+ transform_keys{ |key| key.to_sym rescue key }
+end
+</ruby>
+
+There's also the bang variant +transform_keys!+ that applies the block operations to keys in the very receiver.
+
+NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
+
h5. +stringify_keys+ and +stringify_keys!+
The method +stringify_keys+ returns a hash that has a stringified version of the keys in the receiver. It does so by sending +to_s+ to them: