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 of | Use |
|---|---|
select { }.first | find { } |
map { }.flatten(1) | flat_map { } |
select { }.count | count { } |
map { }.compact | filter_map { } |
each_with_object({}) for counting | tally |
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
- Use
empty?andany?rather than comparingsizeto zero. - Prefer
firstandlastto[0]and[-1]. - Use a
Setwhen you only care about membership and the collection is large. - Break long chains into well named intermediate variables when a reader would otherwise need to hold several steps in their head.