Ruby - Loops and IterationHow can you use a for loop in Ruby to create a hash where keys are numbers 1 to 3 and values are their squares?Ahash = {} for i in 1..3 do hash[i] = i * i endBhash = {} for i in 1..3 do hash[i] = i + i endChash = {} for i in 1..3 do hash[i] = i endDhash = {} for i in 1..3 do hash[i] = i / 2 endCheck Answer
Step-by-Step SolutionSolution:Step 1: Understand the goalCreate a hash with keys 1 to 3 and values as squares of keys.Step 2: Check each option's assignmenthash = {} for i in 1..3 do hash[i] = i * i end assigns i*i which is square. Others assign sums, keys, or division.Final Answer:hash = {} for i in 1..3 do hash[i] = i * i end -> Option AQuick Check:Assign squares as values in hash [OK]Quick Trick: Use hash[key] = value inside for loop [OK]Common Mistakes:Assigning wrong value (sum, division)Not initializing hashUsing wrong operators
Master "Loops and Iteration" in Ruby9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Ruby Quizzes Hashes - Symbol keys vs string keys decision - Quiz 15hard Loops and Iteration - Upto and downto methods - Quiz 12easy Methods - Method naming conventions (? and ! suffixes) - Quiz 12easy Operators and Expressions - Ternary operator - Quiz 3easy Operators and Expressions - Truthy and falsy values (only nil and false are falsy) - Quiz 2easy Operators and Expressions - Ternary operator - Quiz 9hard String Operations - Why strings are mutable in Ruby - Quiz 11easy Variables and Data Types - Type checking with .class and .is_a? - Quiz 1easy Variables and Data Types - Dynamic typing vs strong typing - Quiz 4medium Variables and Data Types - Nil as the absence of value - Quiz 7medium