Skip to content

Instantly share code, notes, and snippets.

@tahb
Last active August 29, 2015 13:57
Show Gist options
  • Save tahb/9640504 to your computer and use it in GitHub Desktop.
Save tahb/9640504 to your computer and use it in GitHub Desktop.
Hash Merge
# 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