How to Add Key-Value to Hash in Ruby: Simple Guide
In Ruby, you add a key-value pair to a hash by using the syntax
hash[key] = value. This assigns the value to the specified key in the hash, creating the pair if it doesn't exist or updating it if it does.Syntax
To add or update a key-value pair in a Ruby hash, use the syntax:
hash[key] = value: Assigns thevalueto thekeyin thehash.hash: The hash variable you want to modify.key: The key where you want to store the value (can be a symbol, string, or other object).value: The data you want to associate with the key.
ruby
hash = {}
hash[:name] = "Alice"Example
This example shows how to create a hash and add a new key-value pair to it. It also updates an existing key's value.
ruby
person = { age: 30 }
person[:name] = "Alice"
puts person
person[:age] = 31
puts personOutput
{:age=>30, :name=>"Alice"}
{:age=>31, :name=>"Alice"}
Common Pitfalls
Some common mistakes when adding key-value pairs to hashes include:
- Using parentheses instead of square brackets, like
hash(key) = value, which causes errors. - Forgetting that keys are case-sensitive and must match exactly.
- Trying to add a key to a frozen hash, which raises an error.
ruby
hash = {}
# Wrong way - causes error:
# hash(:name) = "Alice"
# Right way:
hash[:name] = "Alice"Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Add or update key-value | hash[key] = value | Assigns value to key in hash |
| Access value by key | hash[key] | Retrieves value for key |
| Check if key exists | hash.key?(key) | Returns true if key is present |
| Delete key-value pair | hash.delete(key) | Removes key and its value |
Key Takeaways
Use square brackets with the key to add or update a hash value: hash[key] = value.
Keys can be symbols, strings, or other objects but must be consistent when accessing.
Avoid syntax errors by not using parentheses when assigning values to hash keys.
You cannot modify a frozen hash; it will raise an error if you try to add keys.
Use hash.key?(key) to check if a key exists before adding or updating.