diff options
author | Xavier Noria <fxn@hashref.com> | 2009-09-15 01:21:41 +0200 |
---|---|---|
committer | Xavier Noria <fxn@hashref.com> | 2009-09-15 01:21:41 +0200 |
commit | 08aa954805597e0236c592c2280a91394d22a65f (patch) | |
tree | b512125d140d3f5b2a113435ca6f89cb85427245 /railties/guides/source/active_support_overview.textile | |
parent | a0fb9a6f7c0614358e59bb5f95eef00cba79ab50 (diff) | |
download | rails-08aa954805597e0236c592c2280a91394d22a65f.tar.gz rails-08aa954805597e0236c592c2280a91394d22a65f.tar.bz2 rails-08aa954805597e0236c592c2280a91394d22a65f.zip |
AS guide: documents reverse_merge and reverse_merge!
Diffstat (limited to 'railties/guides/source/active_support_overview.textile')
-rw-r--r-- | railties/guides/source/active_support_overview.textile | 29 |
1 files changed, 28 insertions, 1 deletions
diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index a498849633..442407f916 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -1110,7 +1110,7 @@ By default the root node is "hash", but that's configurable via the <tt>:root</t The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder with the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder. -h4. Deep Merging +h4. Merging Ruby has a builtin method +Hash#merge+ that merges two hashes: @@ -1119,6 +1119,33 @@ Ruby has a builtin method +Hash#merge+ that merges two hashes: # => {:a => 0, :b => 1, :c => 2} </ruby> +Active Support defines a few more ways of merging hashes that may be convenient. + +h5. +reverse_merge+ and +reverse_merge!+ + +In case of collision the key in the hash of the argument wins in +merge+. You can support option hashes with default values in a compact way with this idiom: + +<ruby> +options = {:length => 30, :omission => "..."}.merge(options) +</ruby> + +Active Support defines +reverse_merge+ in case you prefer this alternative notation: + +<ruby> +options = options.reverse_merge(:length => 30, :omission => "...") +</ruby> + +And a bang version +reverse_merge!+ that performs the merge in place: + +<ruby> +options.reverse_merge!(:length => 30, :omission => "...") +</ruby> + +WARNING. Take into account that +reverse_merge!+ may change the hash in the caller, which may or may not be a good idea. + + +h5. +deep_merge+ and +deep_merge!+ + As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins. Active Support defines +Hash#deep_merge+. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash: |