0
0
Rubyprogramming~10 mins

Default values for missing keys 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 create a hash with a default value of 0.

Ruby
counts = Hash.new([1])
Drag options to blanks, or click blank then click option'
A''
Bfalse
Cnil
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using nil as default value returns nil for missing keys, not 0.
Using empty string '' sets default to a string, not a number.
2fill in blank
medium

Complete the code to create a hash with a default value of an empty array.

Ruby
groups = Hash.new([1])
Drag options to blanks, or click blank then click option'
A{}
B[]
Cnil
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces {} creates an empty hash, not an array.
Using nil means missing keys return nil, not an array.
3fill in blank
hard

Fix the error in the code to correctly set a default value that is a new empty array for each missing key.

Ruby
groups = Hash.new { |hash, key| hash[[1]] = [] }
Drag options to blanks, or click blank then click option'
Akey
Bhash
Cgroups
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'hash' instead of 'key' as the index causes an error.
Using 'value' is incorrect because the block only has hash and key parameters.
4fill in blank
hard

Fill both blanks to create a hash that counts occurrences of words.

Ruby
counts = Hash.new([1])
words.each do |word|
  counts[word] = counts[word] [2] 1
end
Drag options to blanks, or click blank then click option'
A0
B+
C-
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' subtracts instead of adding.
Using '*' multiplies, which is incorrect for counting.
5fill in blank
hard

Fill all three blanks to create a hash with default value as a new array and add elements to it.

Ruby
groups = Hash.new { |hash, [1]| hash[[2]] = [3] }
groups[:fruits] << 'apple'
Drag options to blanks, or click blank then click option'
Akey
C[]
D{}
Attempts:
3 left
💡 Hint
Common Mistakes
Using '{}' assigns an empty hash instead of an array.
Using different names for the key parameter causes errors.