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
Blocks, Procs, Lambdas
Use blocks with yield, Procs, lambdas, and the & operator.
Classes and Modules
Define classes with inheritance, mix in modules, and add class methods.
Iterators
Use each, map, select, reduce, group_by, and lazy enumerators.
Strings
Interpolate, trim, split, replace, and pattern-match strings.
Metaprogramming
Define methods dynamically, intercept with method_missing, and build DSLs.
Error Handling
Raise and rescue typed exceptions with ensure and retry.