Hashes
Create a hash
Keys are often symbols in idiomatic Ruby.
user = { name: "Ada", lessons: 4 }
puts user[:name]
user[:lessons] = 5
Read safely
Fetch with a default when a key might be missing.
puts user.fetch(:name)
puts user.fetch(:email, "none")
Iterate
Yield key and value together.
user.each do |key, value|
puts "#{key}=#{value}"
end
Hash habits
- Symbol keys (
:name) are common for fixed fields - String keys appear often with JSON
keysandvalueslist contents- Hashes do not keep numeric indexes like arrays
Comments
One comment per signed-in account. Comments are saved with this page’s URL.