Reading — step 1 of 5
Learn
~1 min readCollections
Hashes are key-value collections. Keys can be anything (most often symbols or strings).
ages = { "Alice" => 30, "Bob" => 25 } # rocket form (any key type)
ages = { alice: 30, bob: 25 } # symbol-key shorthand
puts ages[:alice] # 30
ages[:carol] = 40 # add
ages.delete(:bob)
puts ages.size # 2
ages.each do |name, age|
puts "#{name}: #{age}"
end
Missing keys return nil by default. To set a different default: Hash.new(0) for a counter:
counts = Hash.new(0)
words.each { |w| counts[w] += 1 } # safe even for unseen words
Hash.new { |h, k| h[k] = [] } lets you compute the default on demand — very handy for grouping.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…