Home / Womply Ruby Style Guide

Ruby Collections Style: Arrays, Hashes and Enumerable Idioms

The documentation that used to be at this address is no longer published, and its source was never released under an open license, so it is not reproduced here. This page is an independent guide to the same topic, written for this archive. It is not the project's documentation and is not affiliated with its authors.

Most Ruby code spends its time building, filtering and transforming arrays and hashes. A few consistent habits make that code shorter and much easier to trust.

Use literals

Create empty collections with [] and {} rather than Array.new and Hash.new, unless you need a default value. Use the modern hash syntax when keys are symbols.

options = { timeout: 5, retries: 3 }
counts = Hash.new(0)
words.each { |word| counts[word] += 1 }

Watch out for Hash.new([]): every missing key shares the same array object. Use a block instead: Hash.new { |hash, key| hash[key] = [] }.

fetch when the key must exist

Square brackets return nil for a missing key, which often surfaces as an error far from the cause. Use fetch when a key is required, and give it a default when it is optional.

api_key = config.fetch(:api_key)
region = config.fetch(:region, "us-east-1")

Pick the most specific Enumerable method

Instead ofUse
select { }.firstfind { }
map { }.flatten(1)flat_map { }
select { }.countcount { }
map { }.compactfilter_map { }
each_with_object({}) for countingtally
first_admin = users.find(&:admin?)
tags = posts.flat_map(&:tags).uniq
status_counts = orders.map(&:status).tally

Avoid mutating what you are iterating

Do not add or remove elements from an array while looping over it. Build a new collection with map, select or reject instead. When a collection is meant to be constant, freeze it so accidental changes raise immediately.

VALID_COUNTRIES = %w[US CA GB].freeze

Readability rules

More on Womply Ruby Style Guide

Explore the archive