0
0
Rubyprogramming~10 mins

Hash methods (keys, values, each) in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Akeys
Bvalues
Ceach
Dlength
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.
2fill in blank
medium

Complete 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'
Akeys
Bvalues
Ceach_key
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keys' returns keys, not values.
Using 'each_key' returns an enumerator for keys, not values.
3fill in blank
hard

Fix 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'
Akeys
Bvalues
Ceach
Dmap
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keys' or 'values' returns arrays, not pairs.
Using 'map' returns a new array, not just iteration.
4fill in blank
hard

Fill 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'
A.length
B>
C<
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' filters shorter words.
Forgetting to use '.length' to get word length.
5fill in blank
hard

Fill 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'
Ak.upcase
Bv
Ceach
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'k' instead of 'k.upcase' keeps keys lowercase.
Using 'map' instead of 'each' changes the return type.