0
0
Rubyprogramming~10 mins

Reduce/inject for accumulation 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 sum all numbers in the array using inject.

Ruby
numbers = [1, 2, 3, 4]
total = numbers.[1](0) { |sum, n| sum + n }
puts total
Drag options to blanks, or click blank then click option'
Ainject
Breduce
Cmap
Dselect
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of inject, which returns an array instead of a single value.
Using select, which filters elements but does not accumulate.
2fill in blank
medium

Complete the code to multiply all numbers in the array using reduce.

Ruby
numbers = [2, 3, 4]
product = numbers.[1](1) { |prod, n| prod * n }
puts product
Drag options to blanks, or click blank then click option'
Ainject
Bmap
Creduce
Deach
Attempts:
3 left
💡 Hint
Common Mistakes
Using map which returns an array instead of a single value.
Using each which returns the original array.
3fill in blank
hard

Fix the error in the code to correctly sum the lengths of all words.

Ruby
words = ["apple", "banana", "cherry"]
total_length = words.inject(0) { |sum, word| sum + word.[1] }
puts total_length
Drag options to blanks, or click blank then click option'
Alength
Bcount
Csize
Dlength()
Attempts:
3 left
💡 Hint
Common Mistakes
Using length() with parentheses which is valid but less idiomatic.
Using count which counts elements matching a condition, not length.
4fill in blank
hard

Fill both blanks to create a hash mapping words longer than 5 characters to their lengths.

Ruby
words = ["apple", "banana", "cherry", "date"]
lengths = words.inject({}) { |h, word| (word.[1] [2] 5) ? h.update(word => word.[1]) : h }
puts lengths
Drag options to blanks, or click blank then click option'
Alength
Bsize
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' which selects shorter words.
Using size instead of length, which is acceptable but less common.
5fill in blank
hard

Fill all three blanks to create a hash with uppercase words as keys and original words as values if length greater than 4.

Ruby
words = ["pear", "peach", "plum", "pineapple"]
result = words.inject({}) { |h, word| (word.length [3] 4) ? h.update([1] => [2]) : h }
puts result
Drag options to blanks, or click blank then click option'
Aword.upcase
Bword
C>
Dword.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.length as key instead of value.
Using '<' instead of '>' in the condition.