From 08aa954805597e0236c592c2280a91394d22a65f Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Tue, 15 Sep 2009 01:21:41 +0200 Subject: AS guide: documents reverse_merge and reverse_merge! --- .../guides/source/active_support_overview.textile | 29 +++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) (limited to 'railties/guides') 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 :rootBuilder::XmlMarkup. You can configure your own builder with the :builder option. The method also accepts options like :dasherize 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} +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: + + +options = {:length => 30, :omission => "..."}.merge(options) + + +Active Support defines +reverse_merge+ in case you prefer this alternative notation: + + +options = options.reverse_merge(:length => 30, :omission => "...") + + +And a bang version +reverse_merge!+ that performs the merge in place: + + +options.reverse_merge!(:length => 30, :omission => "...") + + +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: -- cgit v1.2.3