How to Create Hash in Ruby: Syntax and Examples
In Ruby, you create a hash using curly braces
{} with key-value pairs separated by commas. Keys and values are connected by either a hash rocket => or a colon : for symbol keys, like { key: 'value' }.Syntax
A Ruby hash is a collection of key-value pairs enclosed in curly braces {}. Each key is followed by a value, connected by either a hash rocket => or a colon : if the key is a symbol. Multiple pairs are separated by commas.
- Curly braces: Define the hash.
- Keys: Can be symbols, strings, or other objects.
- Values: Any Ruby object.
- Hash rocket (
=>): Used to separate key and value, especially for string keys. - Colon syntax: Used for symbol keys for cleaner code.
ruby
hash1 = { 'name' => 'Alice', 'age' => 30 }
hash2 = { name: 'Bob', age: 25 }Example
This example shows how to create a hash with symbol keys using the colon syntax and how to access values by their keys.
ruby
person = { name: 'Alice', age: 30, city: 'New York' }
puts person[:name]
puts person[:age]
puts person[:city]Output
Alice
30
New York
Common Pitfalls
One common mistake is mixing symbol keys and string keys unintentionally, which can cause key lookup to fail. Also, forgetting to use the correct syntax for keys can lead to errors.
For example, using a string key with colon syntax is invalid:
ruby
# Wrong way:
hash = { 'name:' => 'Alice' } # This creates a string key with colon included
# Right way:
hash = { 'name' => 'Alice' } # String key with hash rocket
hash = { name: 'Alice' } # Symbol key with colon syntaxQuick Reference
| Syntax | Description |
|---|---|
| { key: value } | Hash with symbol keys using colon syntax |
| { 'key' => value } | Hash with string keys using hash rocket |
| hash[:key] | Access value by symbol key |
| hash['key'] | Access value by string key |
Key Takeaways
Use curly braces {} to create a hash with key-value pairs in Ruby.
Symbol keys use colon syntax (e.g., name: 'Alice'), while string keys use hash rockets (e.g., 'name' => 'Alice').
Access hash values by their keys using square brackets, matching the key type exactly.
Avoid mixing symbol and string keys to prevent lookup errors.
Remember that keys can be any object, but symbols and strings are most common.