Hashes

Contents
Hash literals
Read and fetch
Keys values each
Default values

Hash literals

Curly braces group key value pairs into a hash. Symbols written with a trailing colon are the usual keys: short, readable labels for each value. Values may be of any type, mixed freely in one hash.

user = { name: "Ada", age: 36 } puts user[:name] puts user[:age]

Ada
36

Read and fetch

Brackets return nil for a missing key, which is quiet but easy to overlook. The method fetch is stricter: it raises a KeyError for a missing key unless you pass a fallback value. The predicate key? simply reports whether a key is present.

user = { name: "Ada", age: 36 } puts user.fetch(:age) puts user.fetch(:city, "unknown") puts user.key?(:city)

36
unknown
false

Keys values each

The methods keys and values return plain arrays of each side. The method each yields the key and the value together into two block variables. The method length counts the stored pairs.

user = { name: "Ada", age: 36 } puts user.keys.length user.each do |key, value| puts "#{key}: #{value}" end

2
name: Ada
age: 36

Default values

A plain hash answers nil for unknown keys. Passing a default to Hash.new changes that answer, which makes counters tidy. For a default that must stay fresh per key, such as an empty array, use the block form so every key receives its own object.

counts = Hash.new(0) counts["Ada"] += 1 puts counts["Ada"] puts counts["Bob"] lists = Hash.new { |h, k| h[k] = [] } lists["a"].push(1) puts lists["a"].length

1
0
1

The unknown name scores 0 without ever being stored. The block form stores a fresh array for key a, so its length is 1.

Next: Ranges

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: