Syntax
topics = ["Arrays", "Hashes"]
profile = { name: "Ada" }
puts topics[0]
puts profile[:name]Examples
Read by position or by name
The array keeps a reading order; the hash gives names to profile fields. They solve different lookup problems.
topics = ["Arrays", "Hashes"]
profile = { name: "Ada", completed: 2 }
puts topics[0]
puts topics[-1]
puts "#{profile[:name]} completed #{profile[:completed]} topics"
- Output is Arrays, then Hashes, then Ada completed 2 topics. Array index 0 is the first element; -1 counts back from the end.
- The name: syntax creates the symbol key :name. profile[:name] retrieves its value without depending on where the field appears.
- Change completed to 3: only the final message changes. Reordering topics changes the positional lookups instead.
Distinguish missing keys from the wrong key type
A symbol and a string with the same spelling are different hash keys. fetch can supply a deliberate fallback for a missing key.
profile = { name: "Ada", nickname: nil }
p profile[:name]
p profile["name"]
p profile.fetch(:nickname, "No nickname")
p profile.fetch(:city, "Unknown city")
- p displays values with inspect, so output is "Ada", nil, nil, and "Unknown city" on separate lines. Unlike puts, it makes nil visible.
- profile["name"] is nil because only :name exists. Use the key type supplied by your data; for example, parsed JSON commonly has string keys.
- fetch uses its fallback only when the key is absent. :nickname exists with a nil value, so its fallback is not used. Without a fallback, fetch raises KeyError for an absent key.
Best practices
- Use an array when order and numeric positions matter; use a hash when named lookups matter.
- Use fetch when a missing key needs an explicit policy instead of silently treating it as nil.
Runtime & versions
Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Ruby documentation