Hashes Cheat Sheet

Name Description Syntax Examples
Hash literal Create a hash { “key” => “value” } hash = {}
ages = { "Ferdi" => 32, "Hana" => 33, "Mario" => 22 }
Hash.new Create a new empty hash (equivalent to {}) Hash.new hash = Hash.new
Hash access Access a value by its key hash[key] ages["Hana"]
Key deletion Delete a key-value pair by its key hash.delete(key) ages.delete("Mario")
Empty hash Remove all pairs from the hash hash.clear ages.clear
Iterate over hash Iterate over all the pairs in the hash hash.each do |key, value|
end
ages.each do |person, age|
puts "#{person} has value: #{age}"
end
Iterate over pairs Iterate over all the pairs in the hash hash.each_pair do |key, value|
end
ages.each_pair do |person, age|
puts "#{person} has value: #{age}"
end
Get key Get a value for a key, with default value if the key does not exist. hash.fetch(key, default) ages.fetch("Ferdi")
ages.fetch("Hugo", 1)
Key existence Ask the hash if it has a certain key hash.has_key?(key) ages.has_key?("Marion")
Value existence Ask the hash if it has a certain value hash.has_value?(value) ages.has_value?(22)
All keys Get all the keys stored in the hash hash.keys ages.keys
All values Get all the values stored in the hash hash.values ages.values
Merge Merge two hashes hash.merge(other_hash) ages.merge({"Marion" => 30})