Hashes
8 min · Ruby
Store values under named keys instead of numbered positions.
Enemy 1 of 5
Key-value pairs with {}
An array is great when order matters, but sometimes you want to retrieve a value by a meaningful name rather than a numeric position. A hash — Ruby's name for what other languages call a dictionary, map, or associative array — solves that by pairing each value with a key you choose yourself.
You write a hash with curly braces, like { name: "Ada", score: 10 }. The name: value syntax you see here is shorthand for symbol keys (:name), which are the idiomatic default in modern Ruby — symbols are lightweight, immutable identifiers that are cheaper to compare than plain strings, which is why Ruby code favors them for hash keys and similar labels. You can also write string keys the older way, like { "name" => "Ada" }, but symbol keys are what you'll see most often.
You retrieve a value with square brackets and the matching key style: hash[:name] for a symbol key, or hash["key"] for a string key. Using the wrong style — looking up hash["name"] on a hash that was built with symbol keys — silently returns nil instead of raising an error, which is a subtle gotcha worth remembering.
Loading editor...