Challenge - 5 Problems
Hash Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of keys and values methods
What is the output of this Ruby code?
Ruby
h = {a: 1, b: 2, c: 3}
puts h.keys.inspect
puts h.values.inspectAttempts:
2 left
💡 Hint
Remember that Ruby symbols are shown with a colon and strings with quotes.
✗ Incorrect
The keys method returns an array of the hash's keys as symbols, and values returns an array of the values as they are stored (integers here).
❓ Predict Output
intermediate1:30remaining
Using each to iterate over a hash
What does this Ruby code print?
Ruby
h = {x: 10, y: 20}
h.each do |key, value|
puts "#{key}:#{value}"
endAttempts:
2 left
💡 Hint
Look at how the block variables are used inside the string.
✗ Incorrect
The each method yields each key and value pair. The code prints key and value separated by a colon on separate lines.
🧠 Conceptual
advanced1:00remaining
Behavior of keys method on empty hash
What is the result of calling
keys on an empty hash in Ruby?Attempts:
2 left
💡 Hint
Think about what keys exist in an empty hash.
✗ Incorrect
Calling keys on an empty hash returns an empty array because there are no keys.
❓ Predict Output
advanced1:30remaining
Effect of modifying hash inside each
What is the output of this Ruby code?
Ruby
h = {a: 1, b: 2}
h.each do |k, v|
h[k] = v * 2
end
puts h.inspectAttempts:
2 left
💡 Hint
Think about whether modifying values during iteration is allowed.
✗ Incorrect
Modifying the values of existing keys during each is allowed. The values get doubled.
❓ Predict Output
expert2:00remaining
Output of nested each with keys and values
What is printed by this Ruby code?
Ruby
h = {one: [1, 2], two: [3, 4]}
h.each do |key, values|
values.each do |v|
puts "#{key}-#{v}"
end
endAttempts:
2 left
💡 Hint
Look carefully at the nested iteration and string interpolation.
✗ Incorrect
The outer each iterates keys and arrays. The inner each iterates values, printing key-value pairs separated by a dash.