Skip to content
Ruby

Hashes

Build, default, transform, merge, and group with Hash.

By EZ4Code Team
hashdictionary

Code

# Literal
person = { name: "Alice", age: 30, city: "Paris" }
puts person[:name]

# Access with default
counts = Hash.new(0)
"hello world".each_char { |c| counts[c] += 1 }
puts counts.inspect

# Iterate
person.each { |k, v| puts "#{k}: #{v}" }

# Transform values
squared = { a: 1, b: 2, c: 3 }.transform_values { |v| v * v }
puts squared.inspect

# Filter
filtered = person.select { |k, _v| k != :age }
puts filtered.inspect

# Merge
defaults = { timeout: 30, retries: 3 }
opts = { retries: 5 }
merged = defaults.merge(opts) { |_k, d, o| o }
puts merged.inspect

# Invert
puts({ a: 1, b: 2 }.invert.inspect)

# Group by
words = %w[apple banana cherry]
by_len = words.group_by(&:length)
puts by_len.inspect

# Nested access with dig
config = { db: { host: "localhost", port: 5432 } }
puts config.dig(:db, :host)

Explanation

Hashes map keys to values with symbol keys being idiomatic for known fields. Hash.new(0) provides a default value, perfect for tallying without explicit presence checks. Methods like transform_values, merge, group_by, and dig make most bulk operations one-liners.

More Ruby Snippets