liveBook · Manning

Name-value pair

As explained in The Well-Grounded Rubyist, Fourth Edition

A key/value pair, or hash entry, consists of a key and its associated value stored in a hash.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains creation, retrieval, uniqueness, insertion order, iteration representation, filtering, inversion, and mutation edge cases.
Examples
Uses state abbreviations, indexed gemstone pairs, Boolean hash queries, nested contacts, and filtering or inversion examples.
What you can do after
Apply Ruby hash syntax to store, retrieve, iterate, filter, replace, and transform named data.
How it connects
Connects key/value pairs with hashes, arrays, Enumerable methods, iterators, insertion order, and associative-array terminology.

Also explained in

Compare how 11 books explain name-value pair →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.