Complete the code to print each number in the array.
numbers = [1, 2, 3, 4, 5] numbers.[1] do |num| puts num end
The each method is used to iterate over each element in the array and perform an action, like printing.
Complete the code to collect squares of numbers using each.
numbers = [1, 2, 3, 4] squares = [] numbers.[1] do |n| squares << n * n end puts squares
Using each lets you perform actions like adding squares to another array.
Fix the error in the code to print each key and value from the hash.
person = {name: "Alice", age: 30}
person.[1] do |key, value|
puts "#{key}: #{value}"
endThe each method is the correct way to iterate over a hash's keys and values.
Fill both blanks to iterate over an array and print each element with its index.
fruits = ["apple", "banana", "cherry"] fruits.[1].[2] do |fruit, index| puts "#{index}: #{fruit}" end
First call each (which returns the array/enumerator), then chain each_with_index to get both element and index. This demonstrates method chaining with iterators.
Fill all three blanks to create a hash with word lengths for words longer than 3 letters.
words = ["cat", "house", "dog", "elephant"] lengths = {} words.[1] do |[2]| if [2].length > 3 lengths[[3]] = [3].length end end puts lengths
Use each to iterate over the array. Use word consistently as the block parameter name to access each word and conditionally populate the hash with word-length pairs.