Last active
August 29, 2015 13:57
-
-
Save tahb/9640504 to your computer and use it in GitHub Desktop.
Hash Merge
This file contains 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
# Remove duplicate keys | |
array = [ Hash[ burger: 1], Hash[burger: 2, pie: 1] ] | |
array.reduce({}) do |result, department| | |
result.merge(department) do |key, left, right| | |
left + right | |
end | |
end | |
# {:burger=>3, :pie=>1} | |
# Override the right hash with the left | |
default_vehicles = Hash[ car: "red" ] | |
vehicles = Hash[ car: "blue", bike: "green", truck: "yellow" ] | |
vehicles_colours = default_vehicles.reverse_merge(vehicles) | |
# {:car=>"red", :bike=>"green", :truck=>"yellow"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment