Thuta Learning
BasicProgrammingbeginner

Hashes

Relax. We'll talk through this in plain words — no textbook voice.

A Hash is a collection that stores data as key-value pairs. It's widely used to represent things like a user profile, product data, settings, or an API response.

ruby
user = {
  name: "Aung",
  role: "developer",
  city: "Tokyo"
}

puts user[:name]
user[:language] = "Ruby"

user.each do |key, value|
  puts "#{key}: #{value}"
end

name: is the symbol key syntax. To get the value, call it with user[:name]. You can loop over each key/value pair with each.

You should see
Aung name: Aung role: developer city: Tokyo language: Ruby

Info

If a hash key is a string, you access it with user["name"], and if it's a symbol, you access it with user[:name]. The two aren't the same.

Easy traps

  • If you have { name: "Aung" } and call user["name"], you'll get nil back. Make sure the key type matches.
Hashes | Thuta Learning