Skip to content
Justice Tech School

Hashes

Hashes map keys to values. Use symbols for keys, fetch for safe lookup and each for iteration.

Example
h = { name: "Ada", age: 30 }
h[:city] = "Lagos"
puts h[:name], h.fetch(:zip, "none"), h.key?(:age), h.keys.inspect
h.each { |k, v| puts "#{k}=#{v}" }

Result

Ada
none
true
[:name, :age, :city]
name=Ada
age=30
city=Lagos

Exercise

Safe lookup.

h.(:x, 0)

Quiz Test

What does h[:missing] give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.