Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get all keys from the hash.
Ruby
my_hash = {a: 1, b: 2, c: 3}
keys = my_hash.[1]
puts keys Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'values' instead of 'keys' returns the values, not keys.
Using 'each' returns an enumerator, not an array of keys.
✗ Incorrect
The keys method returns an array of all keys in the hash.
2fill in blank
mediumComplete the code to get all values from the hash.
Ruby
my_hash = {x: 10, y: 20, z: 30}
vals = my_hash.[1]
puts vals Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keys' returns keys, not values.
Using 'each_key' returns an enumerator for keys, not values.
✗ Incorrect
The values method returns an array of all values in the hash.
3fill in blank
hardFix the error in the code to print each key and value pair.
Ruby
my_hash = {name: 'Alice', age: 30}
my_hash.[1] do |key, value|
puts "#{key}: #{value}"
end Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keys' or 'values' returns arrays, not pairs.
Using 'map' returns a new array, not just iteration.
✗ Incorrect
The each method iterates over each key-value pair in the hash.
4fill in blank
hardFill both blanks to create a hash of word lengths for words longer than 3 letters.
Ruby
words = ['cat', 'house', 'tree', 'a', 'dog'] lengths = {} words.each do |word| if word.length [2] 3 lengths[word] = word[1] end end puts lengths
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' filters shorter words.
Forgetting to use '.length' to get word length.
✗ Incorrect
Use .length to get the length of each word and > to filter words longer than 3 letters.
5fill in blank
hardFill all three blanks to create a hash with uppercase keys and values greater than 10.
Ruby
data = {"a": 5, "b": 15, "c": 25}
result = {}
data.[3] do |k, v|
if v > 10
result[[1]] = [2]
end
end
puts result Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'k' instead of 'k.upcase' keeps keys lowercase.
Using 'map' instead of 'each' changes the return type.
✗ Incorrect
Use each to iterate, k.upcase for uppercase keys, and v for values.