Hash (Ruby)

A Hash is Ruby's key–value collection (a dictionary or map). You store and look up values by their keys, which are commonly symbols or strings, using curly-brace literals.

Ruby

A Hash maps keys to values: { name: "Ana", age: 30 }. You read with hash[:name], write with hash[:city] = "NYC", and get a default with hash.fetch(:key, default). Symbol keys are conventional and have the clean key: value literal form; any object can be a key.

Hashes are unordered conceptually but actually preserve insertion order in Ruby. They're deeply integrated with method calls: trailing key-value pairs become keyword arguments, which is why configuration and options are usually passed as hashes.

Because Hash includes Enumerable, you can map, select, and each over its pairs: hash.each { |k, v| ... }. Helpful methods include keys, values, merge, dig (for nested access), and transform_values.

Syntax

h = { key1: value1, key2: value2 }
h[:key1]

Examples

Ruby

scores = { ana: 90, sam: 75 }
scores[:max] = 100
puts scores[:ana]
scores.each { |name, score| puts "#{name}: #{score}" }

Output:

90
ana: 90
sam: 75
max: 100

Learn it in a lesson

See also

Back to the Dictionary