0
0
Rubyprogramming~20 mins

Hash methods (keys, values, each) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Hash Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1: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.inspect
A
[:a, :b, :c]
["1", "2", "3"]
B
["a", "b", "c"]
[1, 2, 3]
C
["a", "b", "c"]
["1", "2", "3"]
D
[:a, :b, :c]
[1, 2, 3]
Attempts:
2 left
💡 Hint
Remember that Ruby symbols are shown with a colon and strings with quotes.
Predict Output
intermediate
1: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}" 
end
A
10:x
20:y
B
x:10
y:20
C
[:x, 10]
[:y, 20]
D
x => 10
y => 20
Attempts:
2 left
💡 Hint
Look at how the block variables are used inside the string.
🧠 Conceptual
advanced
1:00remaining
Behavior of keys method on empty hash
What is the result of calling keys on an empty hash in Ruby?
AAn empty array []
Bnil
CRaises an error
DAn array with one nil element [nil]
Attempts:
2 left
💡 Hint
Think about what keys exist in an empty hash.
Predict Output
advanced
1: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.inspect
A{:a=>1, :b=>4}
B{:a=>1, :b=>2}
C{:a=>2, :b=>4}
DRuntimeError: can't modify hash during iteration
Attempts:
2 left
💡 Hint
Think about whether modifying values during iteration is allowed.
Predict Output
expert
2: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
end
A
one-1
one-2
two-3
two-4
B
one-1
two-2
one-3
two-4
C
one-1
one-2
one-3
one-4
D
1-one
2-one
3-two
4-two
Attempts:
2 left
💡 Hint
Look carefully at the nested iteration and string interpolation.