Hashes and Missing Keys
Lesson 16 of 48 in Coddy's Ruby for Python Developers course.
Python dictionaries and Ruby hashes preserve insertion order. Ruby indexing returns nil for a missing key by default, whereas Python dictionary indexing raises KeyError. Ruby fetch can request an exception or supply a fallback; key? distinguishes an absent key from one storing nil. Hash defaults need care: a shared mutable default object can be reused for every missing key. For per-key containers, use a default block that assigns a new container. Here fetch handles a missing key without adding it.
Python: complete program
data = {"b": 2, "a": 1}
print(data.get("x", 9))
print(",".join(data))Ruby: complete program
data = {"b" => 2, "a" => 1}
puts data.fetch("x", 9)
puts data.keys.join(",")Challenge
EasyInput is lowercase words separated by whitespace. Count each word, sort keys alphabetically, and return word:count entries separated by spaces. Empty input returns none.
Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.
Your code goes in exercise.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
def check(value)
raise 'Public API check failed' unless value
end
puts solve(STDIN.read)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Python Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: Borrow3Collections and Blocks
Arrays and IndexingHashes and Missing KeysYielding to a BlockMap and SelectReduce and PredicatesRecap: Repeated CodesPractice on your own: Online Ruby compiler