Ruby - Loops and IterationYou want to sum all numbers in an array using an iterator instead of a loop. Which Ruby code correctly does this?Asum = arr.each { |n| n + n } puts sumBsum = 0 arr.each { |n| sum += n } puts sumCsum = 0 for n in arr sum = n end puts sumDsum = 0 arr.each do |n| sum = n * 2 end puts sumCheck Answer
Step-by-Step SolutionSolution:Step 1: Understand summing with eachInitialize sum to 0, then add each element to sum inside the block.Step 2: Check each optionsum = 0 arr.each { |n| sum += n } puts sum correctly accumulates sum; others overwrite or misuse each.Final Answer:sum = 0 arr.each { |n| sum += n } puts sum -> Option BQuick Check:Sum with iterator = C [OK]Quick Trick: Use sum += n inside each block to accumulate values [OK]Common Mistakes:Overwriting sum instead of addingMisusing each return valueUsing for loop syntax incorrectly
Master "Loops and Iteration" in Ruby9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Ruby Quizzes Arrays - Array modification (push, pop, shift, unshift) - Quiz 13medium Methods - Keyword arguments - Quiz 6medium Methods - Variable-length arguments (*args) - Quiz 4medium Operators and Expressions - Ternary operator - Quiz 5medium Operators and Expressions - Why operators are methods in Ruby - Quiz 8hard Operators and Expressions - Truthy and falsy values (only nil and false are falsy) - Quiz 11easy Operators and Expressions - Range operators (.. and ...) - Quiz 10hard Ruby Basics and Runtime - Why Ruby emphasizes developer happiness - Quiz 13medium Variables and Data Types - Symbol type and immutability - Quiz 3easy Variables and Data Types - Dynamic typing vs strong typing - Quiz 10hard