HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RubyVariablesData TypesOperatorsStringsArraysHash (Dictionary)Conditions (if / else)LoopsMethods (def)Classes
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🗂️ Hash (Dictionary)
🔁 Condition & Loop
🧩 Method & Class
Ruby›Hash (Dictionary)

Hash (Dictionary)

Key-value storage, access, and iterating with each.

Simple enough for a 5-year-old to understand

Create and access a Hash

Example code
1
person = { "name" => "Alex", "age" => 36 }
Key => value.
DataKey => value.
2
puts person["name"]
Access with key: Alex
Output / InputAccess with key: Alex
DataOutput / Input
💡 Hint: A hash is ideal for holding the fields of a record (user, product).

About this topic

A Hash is a collection that holds key-value pairs. The difference from an array is that you access elements using a MEANINGFUL key instead of a sequence number. The search operation is fast and independent of the number of elements.

In Ruby, a hash key can be any object, but symbols are used in practice. A symbol is created only once in memory, is immutable, and is fast to compare — these three characteristics make it ideal for being a key.

The most surprising behavior of a hash is accessing a non-existent key: it doesn't throw an error, it returns nil. A misspelled key name silently produces nil, and the error only appears when that nil is used in a method — far away from the root cause.

What you will learn

  • Creating a hash and accessing it with a key
  • Why symbol keys are preferred
  • That a non-existent key returns nil
  • Providing a default value with fetch
  • Iterating over a hash

When to use?

Hashes are used to hold fields within a record or configuration settings; key names make the code self-explanatory.

If the absence of a key is an error condition, use fetch: it immediately reports the missing key and doesn't propagate nil into the program.

Common mistakes

Wrong

user = { name: "Ali", age: 30 }
puts user["name"]

The key was defined as a symbol but is being queried with a string; a symbol and a string are NOT the same key. The result is nil and no error message is received, only a blank line is printed. This is the most common hash mistake in Ruby.

Correct

user = { name: "Ali", age: 30 }
puts user[:name]

Wrong

settings = { theme: "dark" }
puts settings[:language].upcase

A non-existent key returns nil, then when a method is called on nil, an "undefined method 'upcase' for nil" error occurs. The error appears a step beyond the actual cause. Providing a default value or using fetch solves the problem at the source.

Correct

settings = { theme: "dark" }
puts settings.fetch(:language, "tr").upcase

Wrong

counts = Hash.new(0)
counts[:a] += 1
other = Hash.new([])
other[:x] << 1
other[:y] << 2
puts other[:x].inspect

When an OBJECT is given as the default value, all keys share the SAME object; adding a minus appears in all of them and both values are printed to the screen. Also, the key is never added to the hash. The block format creates a new object for each key.

Correct

counts = Hash.new(0)
counts[:a] += 1
other = Hash.new { |h, k| h[k] = [] }
other[:x] << 1
other[:y] << 2
puts other[:x].inspect

Frequently asked questions

Should I use a symbol or a string as a key?

Symbol. It is created once in memory, immutable, and fast to compare. String keys are only needed when reading external data — for example, when parsing JSON, keys come as strings and you may need to convert them.

Are hashes ordered?

Yes, Ruby hashes preserve the INSERTION order and this behavior is guaranteed. The difference from an array is that you access by key rather than by position, but when iterating, elements come in the order they were added.

Which one should I choose between square brackets and fetch?

If the absence of a key is normal, square brackets and a nil check are sufficient. If the key must definitely exist, use fetch: if it's missing, it errors immediately and shows the problem at the source, preventing nil from spreading into the program.

Summary

A hash holds key-value pairs and access is fast.

A symbol key and a string key are not the same; mixing them up silently produces nil.

A non-existent key returns nil instead of an error.

Passing an object as a default value causes all keys to share it.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code