Ruby - ArraysWhich of the following is the correct syntax to create an array of squares from 0 to 4 using Array.new with a block?AArray.new(5) { |i| i * i }BArray.new(5, i) { i * i }CArray.new(5) do i * i endDArray.new { |i| i * i }Check Answer
Step-by-Step SolutionSolution:Step 1: Recall Array.new with block syntaxThe block form is Array.new(size) { |index| block } where index goes from 0 to size-1.Step 2: Check optionsOnly Array.new(5) { |i| i * i } correctly uses block with index to compute squares.Final Answer:Array.new(5) { |i| i * i } -> Option AQuick Check:Array.new with block uses index for element values [OK]Quick Trick: Use block with index for computed array elements [OK]Common Mistakes:Passing block without sizeWrong block syntaxUsing second argument incorrectly
Master "Arrays" in Ruby9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Ruby Quizzes Arrays - Compact for removing nil values - Quiz 7medium Control Flow - If, elsif, else statements - Quiz 4medium Hashes - Dig method for nested access - Quiz 13medium Methods - Variable-length arguments (*args) - Quiz 6medium Methods - Implicit return (last expression) - Quiz 8hard Operators and Expressions - Conditional assignment (||=) - Quiz 5medium Ruby Basics and Runtime - How Ruby interprets code at runtime - Quiz 14medium Ruby Basics and Runtime - Running scripts with ruby command - Quiz 8hard Ruby Basics and Runtime - What is Ruby - Quiz 10hard Variables and Data Types - Integer and Float number types - Quiz 1easy