Ruby Hash Methods
Hash methods are built-in tools that work on a whole hash. They can list the keys, list the values, ask about one key, and remove a pair.
Listing keys and values
keys lists the names in the order they were added. values lists the scores in that same order.
scores = { "Ana" => 90, "Bo" => 70, "Cy" => 85 }
p scores.keys
p scores.valuesAsking with key?
key? answers whether one key sits in the hash. It answers true for Bo and false for Dee.
scores = { "Ana" => 90, "Bo" => 70 }
puts scores.key?("Bo")
puts scores.key?("Dee")Removing a pair with delete
delete removes the pair stored under Bo. p shows the two pairs that stay.
scores = { "Ana" => 90, "Bo" => 70, "Cy" => 85 }
scores.delete("Bo")
p scoresWalking the pairs with each
each runs the block once per pair. The two names between the | marks take the key and the value of each pair.
scores = { "Ana" => 90, "Bo" => 70 }
scores.each { |name, score| puts "#{name} scored #{score}" }Example
scores = { "Ana" => 90, "Bo" => 70, "Cy" => 85 }
scores.delete("Cy")
p scores.keys
puts scores.key?("Cy")
scores.each { |name, score| puts "#{name} has #{score}" }Key points
- keys gives an array of the keys in the order they were added.
- values gives an array of the values in that same order.
- key? answers true or false for one key.
- delete removes the pair stored under one key.
- each runs a block once per pair in a hash.
- A block for a hash pair names the key first and the value second.
In this example, the scores hash starts with three pairs and delete removes the pair under Cy. The program then prints the keys that stay, asks whether Cy is still a key, and prints one line per pair with each.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What does scores.delete("Bo") do to the hash scores?