Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Ruby Index

🗺️ Hash — Key-value store — ordered since Ruby 1.9

Ruby hashes are ordered key-value pairs. Keys are most commonly Symbols (fast, immutable). Every object can be a key.

📋 Methods & Functions

NameSignatureDescription
[]hash[key] → valueGet value for key
[]=hash[key] = valueSet key to value
fetchhash.fetch(key, default) → valueGet or raise/return default
storehash.store(key, value) → valueSet key to value
deletehash.delete(key) → valueRemove key-value pair
key? / has_key?hash.key?(key) → boolTrue if key exists
value?hash.value?(val) → boolTrue if value exists
keyshash.keys → ArrayReturn all keys
valueshash.values → ArrayReturn all values
eachhash.each {|k,v| block}Iterate key-value pairs
maphash.map {|k,v| expr} → ArrayTransform pairs to array
selecthash.select {|k,v| bool} → HashFilter key-value pairs
rejecthash.reject {|k,v| bool} → HashRemove matching pairs
mergehash.merge(other) → HashReturn merged hash (other wins)
merge!hash.merge!(other) → hashMerge in place
transform_valueshash.transform_values {|v| expr}Transform all values
transform_keyshash.transform_keys {|k| expr}Transform all keys
any?hash.any? {|k,v| bool} → boolTrue if any pair matches
all?hash.all? {|k,v| bool} → boolTrue if all pairs match
counthash.count → IntegerNumber of key-value pairs
empty?hash.empty? → boolTrue if no pairs
to_ahash.to_a → ArrayReturn array of [key,value] pairs
dighash.dig(k1,k2,...) → valueSafe nested access
slicehash.slice(*keys) → HashSub-hash with given keys (Ruby 2.5+)
excepthash.except(*keys) → HashHash without given keys (Ruby 3.0+)
inverthash.invert → HashSwap keys and values
sort_byhash.sort_by {|k,v| key}Sort pairs by key
min_by/max_byhash.min_by {|k,v| key}Pair with min/max key
sumhash.sum {|k,v| expr} → NumberSum block results
filter_maphash.filter_map {|k,v| expr_or_nil}Filter-map pairs
group_by(Enumerable) group_by {|e| key}Group elements into hash
flat_maphash.flat_map {|k,v| [k,v,...]}Flatten pairs

💡 Example Program

Run with ruby script.rb.

# Hash fundamentals
person = { name: "Alice", age: 30, role: "developer" }
puts person[:name]
puts person.fetch(:salary, "not set")
person[:salary] = 95_000
puts person.keys.inspect

# Transformation
puts person.transform_values { |v| v.to_s.upcase }.inspect
puts person.select { |_, v| v.is_a?(Integer) }.inspect

# Word frequency
text = "go ruby go java go ruby rust java go"
freq = text.split.tally
puts freq.sort_by { |_, v| -v }.first(3).map { |k,v| "#{k}:#{v}" }.join(", ")

# Nested hash with dig
config = { db: { host: "localhost", port: 5432 }, cache: { host: "redis" } }
puts config.dig(:db, :host)
puts config.dig(:db, :password).inspect

# merge with block (handle conflicts)
defaults  = { timeout: 30, retries: 3, debug: false }
overrides = { timeout: 60, verbose: true }
merged = defaults.merge(overrides) { |_key, old, new_val| new_val }
puts merged.inspect

# group_by
words = %w[apple banana avocado blueberry cherry apricot]
puts words.group_by { |w| w[0] }.transform_values(&:sort).inspect

# slice / except (Ruby 2.5+ / 3.0+)
h = { a: 1, b: 2, c: 3, d: 4 }
puts h.slice(:a, :c).inspect
# ruby hash_demo.rb

← Array  |  🏠 Index  |  File & IO →