Ruby Hashes
Hashes are like dictionaries in other languages. They store key-value pairs. Ruby gives you two main ways to create them.
The old syntax uses Hash.new and the "rocket" => operator:
person = Hash.new
person = {"name" => "Alice", "age" => 30}
The newer syntax uses symbols with a colon โ cleaner and more idiomatic:
person = {name: "Alice", age: 30}
Access values with the key. Use fetch when you want a safe default if the key doesn't exist:
person[:name] # => "Alice"
person.fetch(:name) # => "Alice"
person.fetch(:email, "N/A") # => "N/A" (default since :email is missing)
You can grab all the keys or values separately, or iterate over them:
person.keys # => [:name, :age]
person.values # => ["Alice", 30]
person.each_key { |k| puts k }
person.each_value { |v| puts v }
Combine two hashes with merge. If both have the same key, the second hash wins:
defaults = {color: "red", size: "medium"}
user_pref = {color: "blue"}
settings = defaults.merge(user_pref)
# => {:color=>"blue", :size=>"medium"}
Hashes also work beautifully as keyword arguments in methods, which we'll see later.
Try it Yourself ->