Created
October 13, 2017 07:22
-
-
Save aren55555/7dd28636036c6e63a0d56132ad2353da to your computer and use it in GitHub Desktop.
Hash merges in Ruby for dmolchan
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
require 'pp' # gives us prety printing | |
users = {} # will be a map of GitHub user name to user info | |
# Add Aren to the map | |
users[:aren55555] = { | |
name: "Aren Patel", | |
company: "BufferBox -> Google -> Nest", | |
location: "Narnia", | |
website: "https://arenpatel.com" | |
} | |
# Add Dima to the map | |
users[:dmolchan] = { | |
name: "Dmitriy Molchan", | |
company: "Nest", | |
location: "San Jose, California", | |
website: nil | |
} | |
puts "Users map: \n#{users.pretty_inspect}\n" # prints the map - cool! | |
others = {} # will be a map of similar structure | |
# Add Sam to this map | |
others[:shwoodard] = { | |
name: "Sam Woodard", | |
comapny: "Google", | |
location: "Woodside, California", | |
website: nil, | |
repos: ["google/jsonapi", "shwoodard/sprites"] | |
} | |
puts "Others map: \n#{others.pretty_inspect}\n" # prints the map - neato! | |
merger1 = users.merge(others) # merges others on top of users, and creates a new map | |
puts "Merger1 map: \n#{merger1.pretty_inspect}\n" # prints the map - sweet! | |
# Add Aren to the others map | |
others[:aren55555] = { | |
repos: ["google/jsonapi", "AMFDPMTE/list"] | |
} | |
users.merge!(others) # merges others into users | |
puts "Users map: \n#{users.pretty_inspect}\n" # prints the map - sweet! | |
# note: that all the keys (:name, :company, :location, :website) from | |
# users[:aren55555] were overwrittien by the keys (just :repos) from | |
# others[:aren5555]. In summary a.merge(b) or a.merge!(b) are just | |
# overwritting the intersecting (common) values in a with the values from | |
# b. The non intersecting keys/values from a and b will be present in the | |
# resultant hash. | |
# | |
# Hash#merge http://ruby-doc.org/core-2.0.0/Hash.html#method-i-merge | |
# Hash#merge! http://ruby-doc.org/core-2.0.0/Hash.html#method-i-merge-21 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment