Complete the code to sum all numbers in the array using inject.
numbers = [1, 2, 3, 4] total = numbers.[1](0) { |sum, n| sum + n } puts total
The inject method is used to accumulate a value by applying the block to each element. Here, it sums all numbers starting from 0.
Complete the code to multiply all numbers in the array using reduce.
numbers = [2, 3, 4] product = numbers.[1](1) { |prod, n| prod * n } puts product
The reduce method multiplies all numbers starting from 1, accumulating the product.
Fix the error in the code to correctly sum the lengths of all words.
words = ["apple", "banana", "cherry"] total_length = words.inject(0) { |sum, word| sum + word.[1] } puts total_length
The length method returns the number of characters in a string. It is used here to sum all word lengths.
Fill both blanks to create a hash mapping words longer than 5 characters to their lengths.
words = ["apple", "banana", "cherry", "date"] lengths = words.inject({}) { |h, word| (word.[1] [2] 5) ? h.update(word => word.[1]) : h } puts lengths
The code creates a hash with words as keys and their lengths as values, but only for words longer than 5 characters.
Fill all three blanks to create a hash with uppercase words as keys and original words as values if length greater than 4.
words = ["pear", "peach", "plum", "pineapple"] result = words.inject({}) { |h, word| (word.length [3] 4) ? h.update([1] => [2]) : h } puts result
The hash keys are uppercase words, values are original words, filtered by length greater than 4.