Complete the code to iterate over the array using an iterator.
numbers = [1, 2, 3, 4] numbers.[1] do |num| puts num end
Ruby prefers each as an iterator to loop over collections because it is more readable and expressive.
Complete the code to sum all elements using an iterator.
numbers = [1, 2, 3, 4] sum = 0 numbers.[1] do |num| sum += num end puts sum
The each method iterates over each element, allowing us to sum them easily.
Fix the error in the iterator method name.
fruits = ['apple', 'banana', 'cherry'] fruits.[1] do |fruit| puts fruit.capitalize end
The correct iterator method is each. Misspelling it causes a method error.
Complete the code to create a hash with word lengths for words longer than 3 letters.
words = ['cat', 'house', 'dog', 'elephant'] lengths = words.inject({}) { |acc, word| if word.length [1] 3 acc.merge({word=> word.length}) end acc }
In Ruby, hashes use => to map keys to values. The condition checks if word length is greater than 3.
Fill both blanks to select even numbers and square them in a hash.
numbers = [1, 2, 3, 4, 5] even_squares = numbers.inject({}) { |acc, num| if num % 2 [2] 0 acc.merge({num=> num[1] 2}) end acc }
Use => to map keys to values in the hash, ** to square numbers, and == to check equality.