Skip to content

Instantly share code, notes, and snippets.

@stevecass
Last active September 4, 2020 13:24
Show Gist options
  • Save stevecass/a91bdcfc8058f19dced1 to your computer and use it in GitHub Desktop.
Save stevecass/a91bdcfc8058f19dced1 to your computer and use it in GitHub Desktop.
Ruby hash recap
h1 = Hash.new # => {}
h2 = Hash.new("a") # => {}
h3 = {} # => {}
h4 = {abc: "def"} # => {:abc=>"def"}
h5 = {:abc => "def"} # => {:abc=>"def"}
h6 = {"abc" => "def"} # => {"abc"=>"def"}
h1["abc"] # => nil
h1.fetch("abc", "kitty") # => "kitty"
h1.fetch("abc") { |x| x + "dbd" } # => "abcdbd"
h1.fetch("abc") { "some_value" } # => "some_value"
h.fetch("abc") # ~> KeyError: key not found: "abc"
h = Hash.new # => {}
h[:one] = 1 # => 1
h[:two] = 2 # => 2
h[:three] = 2 # => 2
h # => {:one=>1, :two=>2, :three=>2}
h.each # => #<Enumerator: {:one=>1, :two=>2, :three=>2}:each>
h.each { |key, value| p "key #{key} maps to #{value}" } # => {:one=>1, :two=>2, :three=>2}
# Output
# >> "key one maps to 1"
# >> "key two maps to 2"
# >> "key three maps to 2"
h.each_pair # => #<Enumerator: {:one=>1, :two=>2, :three=>2}:each_pair>
h.each_pair { |pair| p pair } # => {:one=>1, :two=>2, :three=>2}
# Output:
# >> [:one, 1]
# >> [:two, 2]
# >> [:three, 2]
h.each_key # => #<Enumerator: {:one=>1, :two=>2, :three=>2}:each_key>
h.each_value # => #<Enumerator: {:one=>1, :two=>2, :three=>2}:each_value>
#Again these are more use with blocks. They return the keys and values separately
#Key? and include? are synonyms and examine the keys not the values
h.key? 1 # => false
h.key? :one # => true
h.include? 1 # => false
h.include? :one # => true
#Flatten returns the hash as an array like key1, value1, key2, value2
h.flatten # => [:one, 1, :two, 2, :three, 2]
#Hash does the reverse - turns an array into a hash pairwise
array = ['a', 'b', 'c', 'd'] # => ["a", "b", "c", "d"]
Hash[*array] # => {"a"=>"b", "c"=>"d"}
#Note you need to "splat" the array. Can you think why?
h # => {:one=>1, :two=>2, :three=>2}
other = { three: 3 } # => {:three=>3}
h.merge other # => {:one=>1, :two=>2, :three=>3}
h # => {:one=>1, :two=>2, :three=>3}
h.delete(:one) # => 1
h # => {:two=>2, :three=>3}
h.delete_if { |k, v| v > 2 } # => {:two=>2}
h # => {:two=>2}
h = { one: 1, two: 2, three: 3} # => {:one=>1, :two=>2, :three=>3}
h.keep_if { |k, v| v <= 2 } # => {:one=>1, :two=>2}
h # => {:one=>1, :two=>2}
h[:one] = nil # => nil
h # => {:one=>nil, :two=>2}
h.delete(:one) # => nil
h # => {:two=>2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment