Created
November 30, 2016 17:17
-
-
Save Dania02525/effe7e34ef5a3dd44794c8d63fe2e0c9 to your computer and use it in GitHub Desktop.
Cumulative merge- a non destructive ruby merge operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # rather than blindly overwriting key=>value pairs in the target | |
| # as #merge method, for each matching key found in the target, the | |
| # values are merged, meaning you can add to any level of the hash by | |
| # passing the full key=>value path to the value you wish to add to | |
| def cumulative_merge(target, hash) | |
| if target.keys.include? hash.keys.first | |
| Hash[hash.keys.first, cumulative_merge(target[hash.keys.first], hash[hash.keys.first])] | |
| else | |
| target.merge(hash) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment