Ruby Hashes
A hash is a collection that pairs each key with one value. A program reads a value by naming its key, not by counting places.
Pairs with string keys
Each pair joins a name to an age with the => sign. p prints the hash as one value.
ages = { "Ana" => 30, "Bo" => 25 }
p agesReading a value by its key
Square brackets hold the key Ana. The printed number is the age stored under that key.
ages = { "Ana" => 30, "Bo" => 25 }
puts ages["Ana"]A missing key gives nil
The key Cy is not in the hash. p shows nil as the result of that read.
ages = { "Ana" => 30, "Bo" => 25 }
p ages["Cy"]Adding and changing a pair
A new key adds a pair, and a known key changes its value. p shows the hash after both writes, and the last line counts its pairs.
ages = { "Ana" => 30, "Bo" => 25 }
ages["Cy"] = 40
ages["Bo"] = 26
p ages
puts ages.lengthExample
prices = { "pen" => 2, "book" => 8 }
prices["bag"] = 15
prices["pen"] = 3
puts prices["book"]
puts prices.length
p pricesKey points
- Curly braces hold the pairs of a hash.
- The => sign joins one key to one value.
- Each key appears only once in a hash.
- Square brackets with a key read the value under that key.
- Reading a key that is not in the hash gives nil.
- length counts how many pairs a hash holds.
In this example, the prices hash starts with two pairs. A new pair for bag is added, and the price under pen changes to 3. The program then prints the price of book, counts the pairs, and prints the whole hash.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
The hash is ages = { "Ana" => 30 }. What does p ages["Bo"] print?