A name-value pair, also called a key/value pair or hash entry, stores one key together with its associated value inside a hash. The key identifies the entry used for lookup; the value is the stored data. Ruby hashes allow any Ruby object as a key or value, but each key can occur only once. section 9.1 section 9.3
Work with pairs through ordinary hash operations:
- Add or update a pair with []= or store. Assigning an existing key replaces its old value, while the key keeps its original insertion position. section 9.3.2
- Retrieve a value with []. A missing key produces nil or a configured default; fetch instead raises an exception unless given a fallback. section 9.3.2
- Iterate through a hash one pair at a time. Each pair is yielded as a two-element array, commonly unpacked into separate key and value block parameters. section 10.2
- Select or reject pairs with a block, producing a subhash; compact removes pairs whose values are nil, while invert swaps keys and values and can discard duplicates. section 9.3.5
Looking up a state abbreviation
state_hash = { "Connecticut" => "CT", "Delaware" => "DE", "New Jersey" => "NJ" }\nstate_hash["Connecticut"] # => "CT"\nstate_hash["Wyoming"] # => nil\nstate_hash["Delaware"] = "DEL" # replaces "DE" section 9.3 section 9.3.2
hash = { red: "ruby", white: "diamond", green: "emerald" }
hash.each_with_index {|(key,value),i|
puts "Pair #{i} is: #{key}/#{value}"
}
Inspect pairs as indexed entries while preserving their hash insertion order. section 9.1










